Swift (programming language)

From Bauman National Library
This page was last modified on 8 June 2016, at 21:20.
Paradigm Multi-paradigm (Protocol-oriented programming, object-oriented, functional, imperative, block structured)
Designed by Chris Lattner and Apple Inc.
Developer Apple Inc.
First appeared June 2, 2014; 8 years ago (2014-06-02)[1]
Stable release 2.2 / March 21, 2016; 6 years ago (2016-03-21)
Preview release 2.2-branch / March 28, 2016; 6 years ago (2016-03-28)
Typing discipline Static, strong, inferred
OS Darwin, Linux, FreeBSD
License Apache License 2.0 (Swift 2.2 and later) Proprietary (up to version 2.2)[2][3]
Filename extensions .swift
Website swift.org
Ruby,[4] Rust[5]

Swift is a multi-paradigm, compiled programming language created by Apple Inc. for iOS, OS X, watchOS and tvOS development. 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.


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". On June 2, 2014, the Worldwide Developers Conference (WWDC) application became the first publicly released app written in Swift. 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.

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

Swift reached the 1.0 milestone on September 9, 2014, with the "Gold Master" of Xcode 6.0 for iOS.

On June 8, 2015, Apple Inc. released Swift 2.0 which had increased performance, new exception-handling API, some syntax enhancement and Swift functions access check for targeted operating systems. New refined compiler and standart libraries will be realeased for OS X, iOS, Linux and will obtain open source status.


Swift inherits quite many features from Objective-C, however it is defined by data types instead of pointers which are handled by the compiler. Many script languages work in similar way. 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.

Many language features are run faster comparing to other similar languages, e.g. complex objects sorting is done 3,9 times faster comparing to Python and 1,5 times faster comparing to Objective-C.

Code written in Swift may work together with code written in C, C++ and Objective-C in context of the same project.

Types, variables and scoping

2 string variables concatenation code:

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

Swift includes 3 data access levels: public, internal and private.

Optionals and chaining

Chaining inherently allows to call several tied methods, for example:

 let aTenant = aBuilding.TenantList[5]
 let theirLease = aTenant.leaseDetails
 let leaseStart = theirLease.startDate

May be reduced to:

 let leaseStart = aBuilding.TenantList[5]?.leaseDetails?.startDate

Value types

In contrast to most object-oriented languages, Swift offers built-in support for objects using either pass-by-reference or pass-by-value semantics, the former using the class declaration and the latter using struct. Structs in Swift have almost all the same features as classes; methods, implementing protocols, and using the extension mechanisms. For this reason, Apple refers to all data generically as instances as opposed to objects or values. Structs do not support inheritance, however.

The programmer is free to choose which semantics are more appropriate for each data structure in the application. Larger structures like windows would be defined as classes, allowing them to be passed around as pointers. Smaller structures, like a 2D point, can be defined as structs, which will be pass-by-value and allow direct access to their internal data without a dereference. The performance improvement inherent to the pass-by-value concept is such that Swift uses these types for almost all common data types, including Int and Double, as well as types normally represented by objects, like String and Array. Using value types can result in significant performance improvements in user applications as well.

Protocol-oriented programming

Another key feature of Swift is its use of protocols, known in most modern languages as interfaces.

For example, one might declare a protocol called SupportsToString which ensures that instances that conform to the protocol implement a toString method that returns a String. In Swift, this can be declared with code like this:

 protocol SupportsToString {
     func toString() -> String

This protocol can now be added to String, without access to the base class's source:

 extension String: SupportsToString {
    func toString() -> String {
        return self

Libraries, runtime and development

Swift uses the same runtime as the existing Objective-C system but requires iOS 7 / OS X 10.9 or higher. Swift and Objective-C code can be used in a single program, and by extension, C and C++ as well.

Memory management

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.

Debugging and other elements

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). The request is read (read) by the system, then the system does evalutation (eval) operation and returns (print). Then comes loop.

Similarities to C

  • Most C operators are carried over to Swift, but there are some new operators.
  • Curly braces are used to group statements.
  • 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

  • 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

  • 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 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 prior to Swift 2.0 (though it can be emulated through use of closures).
  • Several notoriously error-prone behaviors of earlier 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.

Example code

 // this is a single line comment using two slashes. /* this is also a comment,
    but written over multiple lines */ /* multiline comments
    /* can be nested! */
    Therefore you can block out code containing multiline
 */ // Swift variables are declared with "var"
 // this is 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 // Like variables, if the type of a constant is omitted,
 // Swift will infer it from the constant's value
 let numberOfApples = 3
 let numberOfOranges = 5 // Values of variables and constants can both 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
 print("Hello, world") // This is an array variable
 var fruits = ["mango", "kiwi", "avocado"] // Example of an if statement; .isEmpty, .count
 if fruits.isEmpty {
     print("No fruits in my array.")
 } else {
     print("There are \(fruits.count) items in my array")
 } // Define a dictionary with four items:
 // Each item has 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 {
     print("\(name) is \(age) years old.")
 } // Functions and methods are both declared with the
 // "func" syntax, and the return type is specified with ->
 func sayHello(personName: String) -> String {
     let greeting = "Hello, \(personName)!"
     return greeting
 } // prints "Hello, Dilan!"
 print(sayHello("Dilan")) // 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 it 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 print(sayAge(personName: "Dilan", personAge: 42))

See also


External links

  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. "Ruby 2.3 on Heroku with Matz". Retrieved January 31, 2016. I’m excited about the safe navigation operator, or “lonely operator.” It’s similar to what we see in other programming languages like Swift and Groovy— it makes it simple to handle exceptions. 
  5. "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.