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
Apple Swift Logo.png
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]
OS iOS, OS X
License undecided[3]
Filename extension(s) .swift
Website developer.apple.com/swift

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,[4] 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, Objective-C++ and Swift code to run within a single program.[5]

History[edit]

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.[6] A beta version of the language was released to registered Apple developers at that time, but Apple does 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.[6]

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

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

Features[edit]

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".[9][10]

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.[11] 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[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 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:

NSMutableString *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"

[12]

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.[13] 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<Int>. As in C#,[14] Swift also allows one to indicate a variable is optional by placing a question mark after the type name, var optionalInteger: Int?.[15] 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,[16] 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.[17] The decision to omit the traditional "protected" scope met with some controversy.[18]

Libraries, runtime and development[edit]

Swift uses the same runtime as the existing Objective-C system on Mac OS and iOS. That means that Swift programs can be run on many existing platforms, including at least some capability under iOS 6 and OS X 10.8.[19] 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.[20]

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

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 at one time had garbage collection for OS X Objective-C, but deprecated it in favor of ARC and in iOS only supports ARC.[22] 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.[23]

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

Similarities to Objective-C[edit]

  • 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[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
  • 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[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!"
println(sayHello("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]

References[edit]

  1. ^ 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." 
  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 D language: these identifiers expand to the location of the caller when evaluated in a default argument list." 
  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. ^ Williams, Owen (June 2, 2014). "Apple announces Swift, a new programming language for iOS". The Next Web. Retrieved June 2, 2014. 
  5. ^ 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. 
  6. ^ a b Platforms State of the Union, Session 102, Apple Worldwide Developers Conference, June 2, 2014
  7. ^ The Swift Programming Language. Apple. June 2, 2014. Retrieved June 2, 2014. 
  8. ^ "Swift Has Reached 1.0". Sep 9, 2014. Retrieved September 10, 2014. 
  9. ^ Metz, Rachel (June 3, 2014). "Apple Seeks a Swift Way to Lure More Developers". Technology Review. 
  10. ^ Weber, Harrison (June 2, 2014). "Apple announces ‘Swift,’ a new programming language for OS X & iOS". VentureBeat. 
  11. ^ "Interacting with C APIs". developer.apple.com. Apple Inc. Retrieved July 15, 2014. 
  12. ^ "Strings and Characters". developer.apple.com. Apple Inc. Retrieved July 16, 2014. 
  13. ^ "Object mutability". developer.apple.com. Apple Inc. Retrieved July 16, 2014. 
  14. ^ "Nullable Types", C# Programming Guide, Microsoft.
  15. ^ "Types". developer.apple.com. Apple Inc. Retrieved July 16, 2014. 
  16. ^ Parker, Greg (Jun 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" 
  17. ^ "Access Control". developer.apple.com. Apple Inc. Retrieved July 22, 2014. 
  18. ^ "No protected access modifier?". devforums.apple.com. July 21, 2014. Retrieved July 28, 2014. (registration required (help)). 
  19. ^ "Do Swift-based apps work on OS X 10.9/iOS 7 and lower?", StackOverflow
  20. ^ "Writing Swift Classes with Objective-C Behavior", Apple Inc.
  21. ^ "Swift and Objective-C in the Same Project", Apple Inc.
  22. ^ "Transitioning to ARC Release Notes", Apple Inc.
  23. ^ Lanier, Brian; Groff, Joe. "Intermediate Swift". Apple. Retrieved July 3, 2014. 
  24. ^ Metz, Cade. "Why Coders Are Going Nuts Over Apple’s New Programming Language". Wired. Retrieved July 16, 2014. 
  25. ^ About Swift, Apple Inc.

External links[edit]