Beruflich Dokumente
Kultur Dokumente
Jacob Brazeal
Bob Jones University
1700 Wade Hampton Blvd
Greenville, SC 29614
jbraz767@students.bju.edu
ABSTRACT benchmarks [7] and supports more platforms. We argue that Swift
We find that Swift is typically more readable and reliable than C++, is the better language for its domain – apps in Apple’s ecosystem –
but these design choices sometimes reduce its writability. We find but is too focused to completely displace C++.
that Swift is the superior programming language in the context of The paper is organized as follows: we provide an overview of
the Apple ecosystem, but is not yet ready to replace C++ in general. the structure and syntax of Swift and describe its processor. Then
follows the section Language Features, where we compare and con-
trast Swift’s data types, variables, expressions, control statements,
1 INTRODUCTION subroutines, and generics with comparable features in C++; and
When, in the course of technical frustrations, it becomes necessary last is our conclusion.
to design a new programming language, the designer(s) must bal-
ance a host of competing goals. How important is speed? What 2 OVERVIEW
about ease of writing new code, or portability? One metric for
In this section, we compare and contrast the structure and basic
evaluating a language is the three R’s of programming language
syntax of C++ and Swift, walk through a sample program in both
design: readability, writability, and reliability. In this paper, we use
languages, and provide detailed instructions on getting the Swift
the three R’s to compare the recently-spawned language Swift to
compiler running on Linux.
the classic C++. We assume that the reader is already familiar with
C++, so the bulk of the paper discusses interesting features of Swift
in the context of the isomorphic feature in C++. 2.1 Structure and Syntax
Swift is Apple’s preferred language for developing apps for the A Swift program is organized into classes and methods, as are C++
macOS and iOS platforms. It was the brainchild of Apple employee programs. However, no ”main” method is used: code not wrapped
Chris Lattner (who is also known for overseeing remarkable projects in method or classes is executed in lexical order. Swift also does not
like the LLVM compiler toolchain and Apple’s XCode environment) distinguish, like C++, between header files and source files: there is
[2]. Lattner began work on Swift in 2010, and it was released in no way to declare a method or class without defining it. For large
2014. In just two years, the language rose to #12 on the TIOBE programs, one simply uses multiple files, where dependencies must
index of language popularity [10]. Swift is a compiled, statically- be compiled first. (Like C++, Swift requires methods and classes
typed, multi-paradigm language, fully supporting object-oriented to be defined before one may call or instantiate them: however,
and functional programming [8]. Lattner states that Swift drew unlike C++, it is possible to declare and define extensions to classes
”ideas from Objective-C, Rust, Haskell, Ruby, Python, C#, CLU, and after the class has been defined, so a class might be declared over
far too many others to list” [2]. Unsurprisingly, he does not name multiple files.)
C++ among his inspirations, since many of Swift’s notable design Swift’s syntax largely fits into the C family of languages: one
choices are safeguards against common C++ bugs. The version of uses curly-braces to define blocks, double-slashes for single line
Swift considered in this paper, Swift4, was released in 2017. comments, and slash-star for multi-line comments. Whitespace is
Our comparison language, C++, was created by Danish academic ignored; object members are accessed using the dot (.). There are
Bjarne Stroustrop in 1979 [6]. C++ built on C, adding classes and a few small breaks with tradition: Semi-colons are not required
a powerful STL (Standard Template Library). Also like Swift, C++ to delimit statements on different lines, and parentheses are not
is a compiled, statically-typed, and multi-paradigm language: it required for if, else, and switch conditionals. Swift is free-form and
supports imperative programming, object-oriented programming, case-sensitive [8].
and treats functions as first-class citizens. C++ is maintained by Figure 1 shows a simple program in Swift, and Figure 2 shows
the ISO (International Standardization Organization), and new ver- the same program translated to C++. Both programs have a static,
sions have been released every 3 years since 2011 (we consider the unsorted list of integers, and ask the user for an index, then provide
2011 version here.) C++ is popular for complex, high-performance the kth-largest number in the list. Here are some notes on the
projects. sample program:
We find in this paper that Swift’s design precludes many common On Line 1, we import the Foundation library; it contains many
C++ type and bounds errors, and that Swift has better tools for of Swift’s core features like classes and strings. On line 3, we use
string processing. C++, however, performs significantly faster in readLine() to input a string. Now we want to convert the string to
an integer, but what if the string is null, or the conversion returns
CpS350’17, Greenville, SC, USA
2016. . null? As we’ll see, Swift requires us to explicitly acknowledge the
DOI: possibility of null variables (also called ”optional types”). The ”?”
1
CpS350’17, Dec 5, Greenville, SC, USA Jacob Brazeal
(like Int, or String, or Character) has both a default and an op- intent when they contain symbols like emoji or diacritics. However,
tional version. Default types can never be nil (Swift’s term for Swift strings are less writable, because this abstract representation
undefined), while optional types can. We immediately see a con- makes it impossible to directly index an array, as one would in
trast with C++: C++ allows reference types to be nil, but not value C++ (see Figure 5 for the cumbersome syntax); the underlying data
types. To declare an optional variable in Swift, one can write: structure is a linked list. It’s still possible to get the raw contents of
let myVar : Int? = 5 , in contrast to declaring the equivalent the strings an array of 8-bit or 16-bit characters, using the properties
default variable, let myVar : Int = 5 . The entire syntactical utf8 and utf16 .
system of Swift is aligned around prodding the code-author toward One other type forming a significant contrast is the pointer. Swift
default types (for example, optional types must be converted to de- has pointers, but they are hidden behind a layer of abstraction not
fault types before they are evaluated), while offering lots of support found in C++. Interestingly, pointers are extremely unwieldy; you
for fallbacks if one tries to use an optional type that is currently must use pointer objects, and specifically state how much memory
nil. Since null-reference errors are some of the most famous and you want to deallocate when freeing pointers. See Figure 4 for
common bugs in C++ programs, this philosophy of Swift marks a example usage of passing a pointer to a function and adjusting
welcome improvement in reliability. Also, since the syntax of the the memory referred to by the pointer: note that memory pointed
language requires one to know at any time whether a variable could to by a pointer object is given by its ”memory” property. While
be nil or not, one can reason more effectively about the behavior of Swift is more reliable than C++ in that it discourages pointers, Swift
the program - an improvement in reliability. pointers are also difficult to read and write. If a program actually
Strings form a rich contrast between Swift and C++. In both required pointers, C++ would be far easier to use.[8]
languages, one can use a native, pared-down string (In Swift, this
is a String, in C++, a char array), or an extended version from
the standard library (Swift’s NSString, C++’s std::string). Swift’s 3.2 Variables
NSString is a reference type, and extends the String, which is a Non-optional types always have a default value (for Ints, this is
value type, by adding a few methods like ”Length.” This contrast 0; for Strings, the empty string; for Bools, false.) Optional types
is less stark than the one in C++: a C string is simply a pointer to have a default value of nil. C++ famously gives global and member
a null-terminated char array, providing no methods, while a C++ variables default values, but does not give defaults to local, prim-
string wraps a pointer to a char array, can be resized, overloads itive types. One must appreciate how Swift heads off undesired
operators and provides many methods. We will focus on Swift’s behavior in this way, showing itself more reliable than C++. Swift
String, since it brings out all the important differences between provides extensive tools to make sure that it is obvious when we are
Swift and C++. Since the String is a value type, it is usually copied manipulating an optionally-typed variable, and to provide a safe
on assignment. (However, as an optimization, Swift won’t copy and explicitly defined way to recover from a nil value (see section
strings when the copy is not modified; it uses a pointer to the 3.3 for some of the operators used).
original string.) The next difference is that a Swift String is more All types are determined at compile time, but the compiler can
abstract than a std::string. Instead of representing a char array, it often determine types itself (from default values, for example) and
represents a collection of Unicode graphemes (code points) that only requires the programmer to annotate ambiguous types. For
may individually take up more than one byte. Thus, Swift strings example, we can write var str = "Hello World!" , and Swift
are more reliable, since they are more likely to reflect a developer’s infers it to be a string. This is one of the few features in Swift that
3
CpS350’17, Dec 5, Greenville, SC, USA Jacob Brazeal
1 1
2 let somePoint = (1 , 1) 2 func sample ( Int : inout number ,
3 switch somePoint { 3 name : String ) -> Int {
4 case (0 , 0): 4 print ( number )
5 print ("\( somePoint ) is at the origin ") 5 print ( name )
6 case (_ , 0): 6 name = name - 1
7 print ("\( somePoint ) is on the x - axis ") 7 return name + " :) "
8 case (0 , _ ): 8 }
9 print ("\( somePoint ) is on the y - axis ") 9
10 case ( -2...2 , -2...2): 10 # call :
11 print ("\( somePoint ) is inside the box ") 11 let num : Int = 4
12 default : 12 sample ( number : num , name : " Joe " )
13 print ("\( somePoint ) is outside of the box ")
13
14 } 14 print ( num )
15 # 3
1 1
2 func someFunction <T: SomeClass , 2 func someFunction <T: Equatable >
3 U : SomeProtocol >( someT : T , someU : U) { 3 (a : T , b : T) -> Boolean {
4 } 4 return a == b
5 }
1
2 func someFunction <T : SomeProtocol , S >
and second parameters automatically to the numbered tokens. The 3 (a : T , b : S)
equivalent lambda in C++ is less compelling, and is found in Fig. 2. 4 where S: Equatable ,
We should also note here that scoping works nearly identically 5 S == T. Child {
in the two languages: Swift, like C++, has global variables and 6 }
block-level scoping, and variables are collected by the garbage col-
lector once they pass out of scope and no other references to them
exist; Swift follows Apple tradition in using reference counting for Figure 13: A where-clause template in Swift.
garbage collection. Notably, this means of collection can prevent
a class of reliability problems with C++ programs, the infamous
”double free.” Notably, as long as one avoids pointers (which are not 4 CONCLUSION
always subject to garbage collection), one should never encounter a On the whole, Swift is more reliable and readable than C++. Many
double-free error in Swift, while the same precaution is insufficient of the most common bugs in C++ programs are difficult to write
when working with C++. [8] in Swift (integer overflow and null references, for example.) Mean-
while, Swift’s advanced switch structures, closures, and ranges are
3.6 Generic Programming more readable than C++’s equivalent (when it exists). Swift is not
always more writable: sometimes because the language requires the
Swift’s generic types are very flexible. To begin, consider the poly- user to write logically complete code, and sometimes to discourage
morphic function shown in Figure 11. We see that we can provide poor practices.
templated class types (the semantics of which are similar to tem- Swift’s main advantage for its user base, though, is that it is a
plated class types in C++: type T must inherit from SomeClass). language designed by Apple for iOS and macOS development. Few
However, types can also implement protocols. languages have well-suited APIs and frameworks for this task, and
What are protocols? Protocols are a way to create more versatile among this group Swift quickly emerged as a leader [9]. It grew from
templates for classes in generic data structures. They are used a new release in 2014 to the the #12 language used by professional
much like the Interface pattern is used in .NET languages. That developers in Stack Overflow’s 2017 developer survey [5]. Swift’s
is, an interface is defined like a class, and whatever methods and main weakness is that it is not used for Android development, so
members it defines must also be implemented by the polymorphic cross-platform languages can be more efficient for developers [1],
class. Notably, in the sample shown, it is not necessary for the class and its star has fallen slightly, according to the TIOBE index, where
U to specifically inherit from the protocol, although it may: it must Swift fell from #10 and #20 in the last year [10].
only include the methods and members defined by the protocol. Ultimately, Swift’s expressiveness and reliability are luxuries
Swift also allows us to require certain properties of types (see that come at the cost of performance, and not everyone can afford
Figure 12). The Equatable restriction requires the object to support to pay that price. However, if Swift can become fully cross-platform,
the ”==” and ”!=” operators; this can be helpful, for instance, when it seems likely that its adoption will only increase.
writing a generic library. In Figure 12, we can pass Ints or Floats
to someFunction, but not user-defined classes without the ’==’ REFERENCES
operator). [1] 2017. Apple’s Swift is Losing Developers to Multiplatform Frameworks.
To make more complex restrictions on types, we can use a (2017). https://www.infoworld.com/article/3231664/application-development/
where clause in our template. (See Figure 13.) In this code, we apples-swift-is-losing-developers-to-multiplatform-frameworks.html
[2] 2017. Chris Lattner’s Homepage. (2017). http://nondot.org/sabre/
require S to be an equatable class, T to implement the protocol [3] 2017. Download Swift. (2017). https://swift.org/download/
SomeProtocol , and for S to be the same type as T’s child Child . [4] 2017. How to set & get value of pointer Swift. (2017). https://stackoverflow.com/
questions/25660299/how-to-set-get-value-of-pointer-swift
[8] [5] 2017. Stack Overflow Developer Survey 2017. (2017). https://insights.
One of the main benefits of having such a flexible and expressive stackoverflow.com/survey/2017
templating language is that we can find out much more easily why [6] 2017. Stroustrop: Biographical Information. (2017). http://www.stroustrup.com/
bio.html
certain code does not compile: we can see immediately which [7] 2017. Swift, C++ Performance. (2017). https://www.primatelabs.com/blog/2014/
where clause, for instance, is triggering an inconsistency. C++’s 12/swift-performance/
[8] 2017. The Swift Programming Language Reference. (2017). https:
templating language is also powerful, but produces notoriously //developer.apple.com/library/content/documentation/Swift/Conceptual/
vague error messages. Swift Programming Language/
6
A Comparison of C++ and Swift CpS350’17, Dec 5, Greenville, SC, USA