Swift (programming language)

From Wikipedia, the free encyclopedia
Jump to: navigation, search
This article is about the Apple programming language. For the parallel scripting language, see Swift (parallel scripting language).
Swift logo.svg
Paradigm Multi-paradigm (object-oriented, functional, imperative, block structured)
Designed by Chris Lattner and Apple Inc.
Developer Apple Inc.
First appeared June 2, 2014; 11 months ago (2014-06-02)[1]
1.2 / April 8, 2015; 55 days ago (2015-04-08)
Static, strong, inferred
License Proprietary software[2][3]
Website developer.apple.com/swift/

Swift is a multi-paradigm, compiled programming language created by Apple Inc. for iOS and OS X development. Introduced at Apple's 2014 Worldwide Developers Conference (WWDC),[7] Swift is designed to work with Apple's Cocoa and Cocoa Touch frameworks and the large body of existing Objective-C code written for Apple products. Swift is intended to be more resilient to erroneous code ("safer") than Objective-C, and also more concise. It is built with the LLVM compiler framework included in Xcode 6, and uses the Objective-C runtime, allowing C, Objective-C, C++ and Swift code to run within a single program,[8] but its proprietary nature may hinder Swift's adoption outside the Apple ecosystem.[9]


Development on Swift began in 2010 by Chris Lattner, with the eventual collaboration of many other programmers at Apple. Swift took language ideas "from Objective-C, Rust, Haskell, Ruby, Python, C#, CLU, and far too many others to list".[4] On June 2, 2014, the Worldwide Developers Conference (WWDC) application became the first publicly released app written in Swift.[10] A beta version of the programming language was released to registered Apple developers at the conference, but the company did not promise that the final version of Swift would be source-compatible with the test version. Apple planned to make source code converters available if needed for the full release.[10]

The Swift Programming Language, a free 500-page manual, was also released at WWDC, and is available on the iBooks Store.[11]

Swift reached the 1.0 milestone on September 9, 2014, with the "Gold Master" of Xcode 6.0 for iOS.[12] Swift 1.1 was released on October 22, 2014, alongside the launch of Xcode 6.1.[13] Swift 1.2 was released on April 8, 2015, in conjunction with Xcode 6.3.[14]


Swift is a replacement for the Objective-C language that employs contemporary programming language theory concepts and strives to present a simpler syntax. During its introduction, it was described simply as "Objective-C without the C".[15][16]

By default, Swift does not expose pointers and other unsafe accessors, contrary to Objective-C, which uses pointers pervasively to refer to object instances. Additionally, Objective-C's use of a Smalltalk-like syntax for making method calls has been replaced with a dot-notation style and namespace system more familiar to programmers from other common OO languages like JavaScript, Java or C#. Swift introduces true named parameters and retains key Objective-C concepts, including protocols, closures and categories, often replacing former syntax with cleaner versions and allowing these concepts to be applied to other language structures, like enums.

Types, variables and optionals[edit]

Under the Cocoa and Cocoa Touch environments, many common classes were part of the Foundation Kit library. This included the NSString string library (using Unicode), the NSArray and NSDictionary collection classes, and others. Obj-C provided various bits of syntactic sugar to allow some of these objects to be created on-the-fly within the language, but once created the objects were manipulated with object calls. For instance, concatenating two NSStrings required method calls similar to this:

NSString *str = @"hello,";
str = [str stringByAppendingString:@" world"];

In Swift, many of these basic types have been promoted to the language's core, and can be manipulated directly. For instance, strings are invisibly bridged to NSString (when Foundation is imported) and can now be concatenated with the + operator, allowing greatly simplified syntax; the previous example becoming:[17]

var str = "hello,"
str += " world"

An important new feature in Swift is option types, which allow references or values to operate in a manner similar to the common pattern in C, where a pointer may refer to a value or may be null. This implies that non-optional types cannot result in a null-pointer error. Optional types are created with the Optional mechanism—to make an Integer that is nullable, one would use a declaration similar to var optionalInteger: Optional<Int>. As in C#,[18] Swift also allows one to indicate a variable is optional by placing a question mark after the type name, var optionalInteger: Int?.[19] Variables or constants that are marked optional either have a value of the underlying type or are nil.

Though omitted in the early betas,[20] Swift supports three access control levels for symbols: public, internal, and private. Unlike many object-oriented languages, these access controls ignore inheritance hierarchies: "private" indicates that a symbol is accessible only in the containing source file, "internal" indicates it is accessible within the containing module, and "public" indicates it is accessible from any module.[21] The decision to omit the traditional "protected" scope met with some controversy.[22]

Libraries, runtime and development[edit]

Swift uses the same runtime as the existing Objective-C system but requires iOS 7 / OS X 10.9 or higher.[23] Swift and Objective-C code can be used in a single program, and by extension, C and C++ as well. In contrast to C however, C++ code cannot be used directly from Swift. It is necessary to create an Obj-C or C wrapper between Swift and C++.[24] In the case of Objective-C, Swift has considerable access to the object model, and can be used to subclass, extend and use Objective-C code to provide protocol support.[25] The inverse is not true: a Swift class cannot be subclassed in Objective-C.[26]

To aid development of such programs, and the re-use of existing code, Xcode 6 offers a semi-automated system that builds and maintains a "bridging header" to expose Objective-C code to Swift. This takes the form of an additional header file that simply defines or imports all of the Objective-C symbols that are needed by the project's Swift code. At that point, Swift can refer to the types, functions, and variables declared in those imports as though they were written in Swift. Objective-C code can also use Swift code directly, by importing an automatically maintained header file with Objective-C declarations the project's Swift symbols. For instance, an Objective-C file in a mixed project called "MyApp" could access Swift classes or functions with the code #import "MyApp-Swift.h". Not all symbols are available through this mechanism, however—use of Swift-specific features like generic types, non-object optional types, sophisticated enums, or even Unicode identifiers may render a symbol inaccessible from Objective-C.[27]

Swift also has limited support for attributes, metadata that is read by the development environment, and is not necessarily part of the compiled code. Like Objective-C, attributes use the @ syntax, but the currently available set is small. One example is the @IBOutlet attribute, which marks a given value in the code as an "outlet", available for use within Interface Builder (IB). An "outlet" is a device that binds the value of the on-screen display to an object in code.

Memory management[edit]

Swift uses Automatic Reference Counting (ARC) to manage memory. Apple used to require manual memory management in Objective-C, but introduced ARC in 2011 to allow for easier memory allocation and deallocation.[28] One problem with ARC is the possibility of creating a strong reference cycle, where instances of two different classes each include a reference to the other, causing them to become leaked into memory as they are never released. Swift provides the weak and unowned keywords that allow the programmer to prevent strong reference cycles from occurring. Typically a parent-child relationship would use a strong reference while a child-parent would use either weak reference, where parents and children can be unrelated, or unowned where a child always has a parent, but parent may not have a child. Weak references must be optional variables, since they can change and become nil.[29]

A closure within a class can also create a strong reference cycle by capturing self references. The programmer can indicate which self references should be treated as weak or unowned using a capture list.

Debugging and other elements[edit]

A key element of the Swift system is its ability to be cleanly debugged and run within the development environment, using a read–eval–print loop (REPL), giving it interactive properties more in common with the scripting capabilities of Python than traditional systems programming languages. The REPL is further enhanced with the new 'playgrounds' concept; 'playgrounds' are interactive views running within the Xcode environment that respond to code or debugger changes on-the-fly.[30] If the code in question changes over time or with regard to some other ranged input value, the view can be used with the Timeline Assistant to demonstrate the output in an animated fashion. Apple claims that Swift "is the first industrial-quality systems programming language that is as expressive and enjoyable as a scripting language".[31]

Similarities to C[edit]

  • Most C operators are carried over to Swift, but there are some new operators.
  • Curly braces are used to group statements into closures.
  • Variables are assigned using an equals sign, but compared using two consecutive equals signs. A new identity operator, ===, is provided to check if two data elements refer to the same object.
  • Control statements, for, while, if, switch are similar, but have extended functionality, e.g. a for in that iterates over any collection type, a switch that takes non-integer cases, etc.

Similarities to Objective-C[edit]

  • Basic numeric types (Int, UInt, Float, Double)
  • Square brackets are used with arrays, both to declare them and to get a value at a given index in one of them.
  • Class methods are inherited, just like instance methods; self in class methods is the class the method was called on.

Differences from Objective-C[edit]

  • Statements do not need to end with a semicolon (;), though they must be used to allow more than one statement on a line.
  • Header files are not required.
  • Uses weak typing/Type inference.
  • Generic programming.
  • Functions are first-class objects.
  • Enumeration cases can have associated data (algebraic data types).
  • Operators can be redefined for classes (operator overloading), and new operators can be created.
  • Strings fully support Unicode. Most Unicode characters can be used in either identifiers or operators.
  • No exception handling (though it can be emulated through use of closures)[32]
  • Several notoriously error-prone behaviors of C-family languages have been changed:
    • Pointers are not exposed by default. There is no need for the programmer to keep track of and mark names for referencing or de-referencing.
    • Assignments do not return a value. This prevents the common mistake of writing i=0 instead of i==0 by throwing a compile-time error.
    • No need to use break statements in switch blocks. Individual cases do not fall through to the next case unless the fallthrough statement is used.
    • Variables and constants are always initialized and array bounds are always checked.
    • Integer overflows, which result in undefined behavior for signed integers in C, are trapped as a run-time error in Swift. Programmers can choose to allow overflows by using the special arithmetical operators &+, &-, &*, &/ and &%. The properties min and max are defined in Swift for all integer types and can be used to safely check for potential overflows, as opposed to relying on constants defined for each type in external libraries.

Comparing with Python[edit]

Python is one of the languages that helped inspire Swift.[33]

  • Both languages feature Read–eval–print loop (REPL) development environments
  • Conditional statements are similar for, if, while
  • Swift is a compiled language while standard Python is interpreted
  • Swift has more complex variable types such as UInt32, StringLiteralConvertible, etc.
  • Swift uses curly braces to group statements.
  • Whitespace is not significant
  • Python doesn't employ var or let

Example code[edit]

// this is a single line comment using two slashes.
/* this is also a comment,
   but written over multiple lines */
/* multiline comments
   /* can be nested! */
   so that you can block out code containing multiline comments
// Swift variables are declared with "var" followed by a name, a type, and a value
var explicitDouble: Double = 70
// if the type is omitted, Swift will infer it from the variable's initial value
var implicitInteger = 70
var implicitDouble = 70.0
var 國 = "美國"
// Swift constants are declared with "let" followed by a name, a type, and a value
let numberOfBananas: Int = 10
// if the type is omitted, Swift will infer it from the constant's value
let numberOfApples = 3
let numberOfOranges = 5
// values of variables and constants can be interpolated in strings as follows
let appleSummary = "I have \(numberOfApples) apples."
let fruitSummary = "I have \(numberOfApples + numberOfOranges) pieces of fruit."
// in playgrounds, code can be placed in the global scope
println("Hello, world")
// define an array
var fruits = ["mango", "kiwi", "avocado"]
// example of if statement; .isEmpty, .count
if fruits.isEmpty {
    println("No fruits in my array.")
} else {
    println("There are \(fruits.count) items in my array")
// define a dictionary with four items, each with a person's name and age
let people = ["Anna": 67, "Beto": 8, "Jack": 33, "Sam": 25]
// now we use Swift's flexible enumerator system to extract both values in a single loop
for (name, age) in people {
    println("\(name) is \(age) years old.")
// functions and methods are declared with the "func" syntax
// the return type is specified with ->
func sayHello(personName: String) -> String {
    let greeting = "Hello, " + personName + "!"
    return greeting
// prints "Hello, Jane!"
// parameter names can be made external and required for calling
// the external name can be the same as the parameter name by
// prefixing with an octothorpe (#)
// or can be defined separately.
func sayAge(#personName: String, personAge Age: Int) -> String {
    let result = "\(personName) is \(Age) years old."
    return result
// we can also specify the name of the parameter
println(sayAge(personName: "Jane", personAge: 42))

See also[edit]


  1. ^ "Swift Has Reached 1.0". Apple. September 9, 2014. Retrieved March 8, 2015. 
  2. ^ "Swift, Objectively". Swift is proprietary and closed: It is entirely controlled by Apple and there is no open source implementation. 
  3. ^ Lattner, Chris (June 11, 2014). "Re: [LLVMdev] [cfe-dev] [ADVERTISEMENT] open positions in Apple's Swift compiler team". Retrieved June 12, 2014. You can imagine that many of us want it to be open source and part of llvm, but the discussion hasn't happened yet, and won't for some time. 
  4. ^ a b Lattner, Chris (June 3, 2014). "Chris Lattner's Homepage". Chris Lattner. Retrieved June 3, 2014. I started work on the Swift Programming Language in July of 2010. I implemented much of the basic language structure, with only a few people knowing of its existence. A few other (amazing) people started contributing in earnest late in 2011, and it became a major focus for the Apple Developer Tools group in July 2013 [...] drawing ideas from Objective-C, Rust, Haskell, Ruby, Python, C#, CLU, and far too many others to list. 
  5. ^ "Building assert() in Swift, Part 2: __FILE__ and __LINE__ - Swift Blog -". Apple Developer. Retrieved September 26, 2014. Swift borrows a clever feature from the D language: these identifiers expand to the location of the caller when evaluated in a default argument list. 
  6. ^ "RFC for `if let` expression". Retrieved December 4, 2014. The `if let` construct is based on the precedent set by Swift, which introduced its own `if let` statement. 
  7. ^ Williams, Owen (June 2, 2014). "Apple announces Swift, a new programming language for iOS". The Next Web. Retrieved June 2, 2014. 
  8. ^ Timmer, John (June 5, 2014). "A fast look at Swift, Apple's new programming language". Ars Technica. Condé Nast. Retrieved June 6, 2014. 
  9. ^ "Swift, Objectively". Apple's continued insistence on a closed ecosystem is a missed opportunity to interact productively with developers. 
  10. ^ a b Platforms State of the Union, Session 102, Apple Worldwide Developers Conference, June 2, 2014
  11. ^ The Swift Programming Language. Apple. June 2, 2014. Retrieved June 2, 2014. 
  12. ^ "Swift Has Reached 1.0". September 9, 2014. Retrieved September 10, 2014. 
  13. ^ "Xcode 6.1 Release Notes". October 22, 2014. Retrieved January 23, 2015. 
  14. ^ "Xcode 6.3 Release Notes". April 8, 2015. Retrieved April 8, 2015. 
  15. ^ Metz, Rachel (June 3, 2014). "Apple Seeks a Swift Way to Lure More Developers". Technology Review. 
  16. ^ Weber, Harrison (June 2, 2014). "Apple announces ‘Swift,’ a new programming language for OS X & iOS". VentureBeat. 
  17. ^ "Strings and Characters". developer.apple.com. Apple Inc. Retrieved July 16, 2014. 
  18. ^ "Nullable Types", C# Programming Guide, Microsoft.
  19. ^ "Types". developer.apple.com. Apple Inc. Retrieved July 16, 2014. 
  20. ^ Parker, Greg (June 2, 2014). "Access modifiers in Swift (private, protected, public)". devforums.apple.com. Retrieved July 16, 2014. (registration required (help)). We don't usually promise anything for the future, but in this case we are making an exception. Swift will have access control mechanism 
  21. ^ "Access Control". developer.apple.com. Apple Inc. Retrieved July 22, 2014. 
  22. ^ "No protected access modifier?". devforums.apple.com. July 21, 2014. Retrieved July 28, 2014. (registration required (help)). 
  23. ^ "Do Swift-based apps work on OS X 10.9/iOS 7 and lower?", StackOverflow
  24. ^ "Using Swift with Cocoa and Objective-C: Basic Setup". apple.com. January 6, 2015. 
  25. ^ "Writing Swift Classes with Objective-C Behavior", Apple Inc.
  26. ^ "Migrating Your Objective-C Code to Swift". 
  27. ^ "Swift and Objective-C in the Same Project", Apple Inc.
  28. ^ "Automatic Reference Counting", Apple Inc.
  29. ^ Lanier, Brian; Groff, Joe. "Intermediate Swift". Apple. Retrieved July 3, 2014. 
  30. ^ Metz, Cade. "Why Coders Are Going Nuts Over Apple’s New Programming Language". Wired. Retrieved July 16, 2014. 
  31. ^ About Swift, Apple Inc.
  32. ^ "Error-Handling in Swift-Language". stackoverflow.com. 
  33. ^ Lattner, Chris (June 3, 2014). "Chris Lattner's Homepage". Chris Lattner. Retrieved June 3, 2014. I started work on the Swift Programming Language in July of 2010. I implemented much of the basic language structure, with only a few people knowing of its existence. A few other (amazing) people started contributing in earnest late in 2011, and it became a major focus for the Apple Developer Tools group in July 2013 [...] drawing ideas from Objective-C, Rust, Haskell, Ruby, Python, C#, CLU, and far too many others to list. 

External links[edit]