World Library  
Flag as Inappropriate
Email this Article

Swift (programming language)

Article Id: WHEBN0042946389
Reproduction Date:

Title: Swift (programming language)  
Author: World Heritage Encyclopedia
Language: English
Subject: Generational list of programming languages, IOS, Null coalescing operator, Xcode, Nullable type
Publisher: World Heritage Encyclopedia

Swift (programming language)

Paradigm(s) multi-paradigm (object-oriented, functional, imperative, block structured)
Designed by Chris Lattner and Apple Inc.
Developer Apple Inc.
Appeared in 2014
Stable release 1.1
Typing discipline static, strong, inferred
Influenced by Objective-C, Rust, Haskell, Ruby, Python, Scala, C#, CLU,[1] D[2]
Influenced Rust[3]
License Proprietary software[4]
Filename extension(s) .swift
Website /

Swift is a multi-paradigm compiled programming language created by Apple for iOS and OS X development. Introduced at Apple's 2014 Worldwide Developers Conference,[5] 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 (the same idea can be expressed with a smaller quantity of code). It is built with the LLVM compiler included in Xcode 6, and uses the Objective-C runtime, allowing C, Objective-C, C++ and Swift code to run within a single program.[6]


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

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

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


Swift is, in large part, a reimagining of the Objective-C language using modern concepts and syntax. During its introduction, it was described simply as "Objective-C without the C".[10][11]

Swift does not create pointers and other unsafe accessors by default, contrary to Objective-C which made widespread use of pointers to refer to objects, as well as their traditional use in embedded C-language code, although unsafe pointers can be created explicitly.[12] 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 in common with other C-derived modern languages like 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

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 many 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 be first-class citizens of the language 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
var str = "hello,"
str += " world"

Foundation kit almost always included two versions of its major classes, a mutable version that could be modified at runtime, and an immutable version that could only be created and read from.[14] Swift continues this tradition, but does so in a more generalized way that can be extended to any value type; declaring a value to be a constant, using the let keyword, produces an immutable type and can be applied to both complex value types as well as base types. The immutable constants can be created at any time in the program, and do not have to be created in the setup code of a program. Mutable values are declared using the var keyword.

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. As in C#,[15] Swift also allows one to indicate a variable is optional by placing a question mark after the type name, var optionalInteger: Int?.[16] Variables or constants that are marked optional either have a value of the underlying type or are nil. An advantage to explicitly declaring types as optional means the programmer using Swift knows immediately which variables have to be tested for null and which do not, reducing the chance for the otherwise common is-null errors.

Though omitted in the early betas,[17] 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.[18] The decision to omit the traditional "protected" scope met with some controversy.[19]

Libraries, runtime and development

Swift uses the same runtime as the existing Objective-C system on OS X and iOS. This means that Swift programs can be run on many existing platforms, including at least some capability under iOS 6 and OS X 10.8.[20] More importantly, this means Swift and Objective-C code can be used in a single program, and by extension, C and C++ as well. 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.[21]

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.[22]

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

Swift uses Automatic Reference Counting (ARC) to manage memory. Apple at one time had garbage collection for OS X Objective-C, but deprecated it in favor of ARC and in iOS only supports ARC.[23] 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. 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.[24]

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

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.[25] 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."[26]

Similarities to Objective-C

  • Basic numeric types (Int, UInt, Float, Double)
  • 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.
  • Square brackets are used with arrays, both to declare them and to get a value at a given index in one of them.
  • 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.
  • 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
  • Strong 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
  • 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. Thus the common mistake of writing if (i=0) when if (i==0) is meant will cause 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.
    • Overflows, which are undefined behaviors for signed integers in C, are trapped as a run-time error, but programmers can choose to allow overflows by using the special arithmetical operators &+, &-, &*, &/ and &%. Properties min and max are defined in Swift for all integer types and can be used to safely check for potential overflows, as contrasted with 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! */
   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


  1. ^ a b  
  2. ^ "Building assert() in Swift, Part 2: __FILE__ and __LINE__ - Swift Blog -". Apple Developer. Retrieved September 26, 2014. Swift borrows a clever feature from the  
  3. ^ "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. 
  4. ^  
  5. ^ Williams, Owen (June 2, 2014). "Apple announces Swift, a new programming language for iOS".  
  6. ^ Timmer, John. A fast look at Swift, Apple’s new programming language "A fast look at Swift, Apple's new programming language". Ars Technica. Retrieved June 6, 2014. 
  7. ^ a b Platforms State of the Union, Session 102, Apple Worldwide Developers Conference, June 2, 2014
  8. ^ The Swift Programming Language.  
  9. ^ "Swift Has Reached 1.0". Sep 9, 2014. Retrieved September 10, 2014. 
  10. ^ Metz, Rachel (June 3, 2014). "Apple Seeks a Swift Way to Lure More Developers".  
  11. ^ Weber, Harrison (June 2, 2014). "Apple announces ‘Swift,’ a new programming language for OS X & iOS".  
  12. ^ "Interacting with C APIs".  
  13. ^ "Strings and Characters".  
  14. ^ "Object mutability".  
  15. ^ "Nullable Types", C# Programming Guide, Microsoft.
  16. ^ "Types".  
  17. ^ Parker, Greg (Jun 2, 2014). "Access modifiers in Swift (private, protected, public)". 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 
  18. ^ "Access Control".  
  19. ^ "No protected access modifier?". July 21, 2014. Retrieved July 28, 2014. (registration required (help)). 
  20. ^ "Do Swift-based apps work on OS X 10.9/iOS 7 and lower?", StackOverflow
  21. ^ "Writing Swift Classes with Objective-C Behavior", Apple Inc.
  22. ^ "Swift and Objective-C in the Same Project", Apple Inc.
  23. ^ "Transitioning to ARC Release Notes", Apple Inc.
  24. ^ Lanier, Brian; Groff, Joe. "Intermediate Swift". Apple. Retrieved July 3, 2014. 
  25. ^ Metz, Cade. "Why Coders Are Going Nuts Over Apple’s New Programming Language".  
  26. ^ About Swift, Apple Inc.

External links

  • Swift – official site at Apple
  • Swift Blog - Apple Developer – official news and information on Swift, from Apple
  • Swift Pre-Release documentation at Apple iOS Developer Library
This article was sourced from Creative Commons Attribution-ShareAlike License; additional terms may apply. World Heritage Encyclopedia content is assembled from numerous content providers, Open Access Publishing, and in compliance with The Fair Access to Science and Technology Research Act (FASTR), Wikimedia Foundation, Inc., Public Library of Science, The Encyclopedia of Life, Open Book Publishers (OBP), PubMed, U.S. National Library of Medicine, National Center for Biotechnology Information, U.S. National Library of Medicine, National Institutes of Health (NIH), U.S. Department of Health & Human Services, and, which sources content from all federal, state, local, tribal, and territorial government publication portals (.gov, .mil, .edu). Funding for and content contributors is made possible from the U.S. Congress, E-Government Act of 2002.
Crowd sourced content that is contributed to World Heritage Encyclopedia is peer reviewed and edited by our editorial staff to ensure quality scholarly research articles.
By using this site, you agree to the Terms of Use and Privacy Policy. World Heritage Encyclopedia™ is a registered trademark of the World Public Library Association, a non-profit organization.

Copyright © World Library Foundation. All rights reserved. eBooks from Project Gutenberg are sponsored by the World Library Foundation,
a 501c(4) Member's Support Non-Profit Organization, and is NOT affiliated with any governmental agency or department.