Swift
Swift language reference: numbers, collections, loops, functions, closures, structs and classes, protocols and optionals.
13 min readUpdated
Swift is Apple’s general-purpose language for iOS, macOS, watchOS and tvOS apps, and it also runs on Linux and Windows. This note is a compact reference of the language basics, with notes for developers coming from Java: number types, collections, type annotations, loops, functions, closures, structs and classes, extensions, protocols and optionals.
Decimals and integers
- When you create a floating-point number, Swift infers it as a
Double, short for “double-precision floating-point number”. - Swift infers
IntorDoublefrom the literal you write:let a = 3is anInt,let b = 3.0is aDouble. - Integers and decimals are different types and Swift does not mix them silently. Integers are always exact and decimals are not, so you have to convert explicitly, for example
Double(a) + b.
Older APIs use CGFloat. Since Swift 5.5 the compiler converts between CGFloat and Double implicitly, so you can treat a CGFloat parameter as a Double.
Collection types
Swift has three primary collection types:
- Arrays are ordered collections of values. The same value can appear several times at different positions.
- Sets are unordered collections of unique values.
- Dictionaries are unordered collections of key-value pairs.
All three store values of a single type.
Sets
Use a set instead of an array when the order of items is not important, or when each item must appear only once. The following example creates an empty set and a set with three items, then iterates over it:
var letters = Set<Character>()print("letters is of type Set<Character> with \(letters.count) items.")// Prints "letters is of type Set<Character> with 0 items."
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
for genre in favoriteGenres { print("\(genre)")}// Prints the three genres in no particular orderA set has no defined ordering, so the loop can print the items in any order. Use favoriteGenres.sorted() when you need a stable order.
Dictionaries
A dictionary is similar to a Java Map: it cannot contain duplicate keys, and each key maps to at most one value. Keys and values can be of any type, as long as the key type is hashable:
let person = [ "name": "John Doe", "title": "Mr", "location": "US"]let hasGraduated = [ "Eric": false, "Maeve": true, "Otis": false,]let olympics = [ 2012: "London", 2016: "Rio de Janeiro", 2021: "Tokyo"]You can also create an empty dictionary with explicit key and value types, then set the keys one by one:
var heights = [String: Int]()heights["Yao Ming"] = 229heights["Shaquille O'Neal"] = 216heights["LeBron James"] = 206Reading a key returns an optional, because the key may be missing. See Optionals for how to unwrap it or give a default value.
Type annotations
Swift infers types from the initial value, but a type annotation lets you state the type explicitly. Annotations are required when you create an empty collection without an initial value to infer from:
let surname: String = "Lasso"var score: Int = 0let pi: Double = 3.141var isAuthenticated: Bool = truevar albums: [String] = ["Red", "Fearless"] // Arrayvar user: [String: String] = ["id": "@twostraws"] // Dictionaryvar books: Set<String> = Set(["The Bluest Eye", "Foundation", "Girl, Woman, Other"]) // Setvar teams: [String] = [String]() // Empty array of stringsvar cities: [String] = [] // Empty array of stringsvar clues = [String]() // Empty array of stringsThe last three lines are equivalent ways to create an empty array of strings.
Loops
A for-in loop iterates over an array, a range or any other sequence. 1...12 is a closed range (1 to 12 inclusive) and 1..<5 is a half-open range (1 to 4). Use _ when you do not need the loop variable:
// Loop over an array of stringslet platforms = ["iOS", "macOS", "tvOS", "watchOS"]for os in platforms { print("Swift works great on \(os).")}
// Loop over the closed range [1, 12]for i in 1...12 { print("5 x \(i) is \(5 * i)")}
// Loop over the half-open range [1, 5)for i in 1..<5 { print("Counting 1 up to 5: \(i)")}
// Loop without a loop variablevar lyric = "Haters gonna"for _ in 1...5 { lyric += " hate"}A while loop checks its condition before each iteration:
var countdown = 5while countdown > 0 { print("\(countdown)…") countdown -= 1}A repeat-while loop checks its condition after each iteration, so the body always runs at least once:
var attempts = 0repeat { attempts += 1} while attempts < 3Inside any loop body:
continuestops the current iteration and jumps to the next item.breakexits the loop immediately and skips all remaining iterations.
Functions
Return values
A function declares its return type after ->. When the body is a single expression, you can omit return:
func isUppercase(string: String) -> Bool { string == string.uppercased()}To return several values, you can use an array or a dictionary as the return type. The two functions below are alternatives:
// Returns the parts of the name as an arrayfunc getUser() -> [String] { ["Taylor", "Swift"]}// Returns the parts of the name as a dictionaryfunc getUser() -> [String: String] { [ "firstName": "Taylor", "lastName": "Swift" ]}The recommended way is a tuple. A tuple groups several values into one value; it has a fixed size and each element can have its own type. Elements can be named or accessed by position:
func getUser() -> (firstName: String, lastName: String) { (firstName: "Taylor", lastName: "Swift")}let user = getUser()print("Name: \(user.firstName) \(user.lastName)")func getUser() -> (String, String) { ("Taylor", "Swift")}let user = getUser()print("Name: \(user.0) \(user.1)")You can destructure the returned tuple into separate constants:
let (firstName, lastName) = getUser()print("Name: \(firstName) \(lastName)")If you do not need every value, use _ to ignore that part of the tuple:
let (firstName, _) = getUser()print("Name: \(firstName)")Customize parameter labels
By default, callers must write the parameter name as a label. An underscore before the parameter name removes the external label:
// Declared without an underscore: the caller writes the labelfunc isUppercase(string: String) -> Bool { string == string.uppercased()}let result = isUppercase(string: "HELLO, WORLD")// Declared with an underscore: the caller omits the labelfunc isUppercase(_ string: String) -> Bool { string == string.uppercased()}let result = isUppercase("HELLO, WORLD")A parameter can also have separate external and internal names. This helps when the label that reads best at the call site is a reserved keyword such as for. Using for as the only name does not work, because for cannot be used as a value inside the function body:
func printTimesTables(for: Int) { for i in 1...12 { print("\(i) x \(for) is \(i * for)") // Error: `for` is a keyword here }}Give the parameter an internal name and keep for as the external label:
func printTimesTables(for number: Int) { for i in 1...12 { print("\(i) x \(number) is \(i * number)") }}printTimesTables(for: 5)Callers still write for:, and the body uses number.
Closures
Closures are self-contained blocks of functionality that can be passed around in your code, similar to lambdas in Java. A closure can capture and store references to constants and variables from the context where it is defined; this is called closing over those values.
The general form of a closure expression is:
{ (parameters) -> return type in statements}The following example passes a closure to sorted(by:) so that “Suzanne” always comes first and the other names are sorted alphabetically:
let team = ["Gloria", "Suzanne", "Piper", "Tiffany", "Tasha"]let captainFirstTeam = team.sorted(by: { (name1: String, name2: String) -> Bool in if name1 == "Suzanne" { return true } else if name2 == "Suzanne" { return false } return name1 < name2})With shorthand argument names, Swift names the parameters $0, $1 and so on. Combined with trailing closure syntax, a reverse sort becomes one line:
let reverseTeam = team.sorted { $0 > $1 }Functions as parameters
A function can take several closures as parameters, and the caller can pass them all as trailing closures (Swift 5.3 and later). This function accepts three closures that take no parameters and return nothing:
func doImportantWork(first: () -> Void, second: () -> Void, third: () -> Void) { print("About to start first work") first() print("About to start second work") second() print("About to start third work") third() print("Done!")}
doImportantWork { print("This is the first work")} second: { print("This is the second work")} third: { print("This is the third work")}The first trailing closure has no label; the following ones use their parameter labels.
Structures and classes
Swift does not need separate interface and implementation files for custom structures and classes. Both can:
- Define properties to store values
- Define methods to provide functionality
- Define subscripts to give access to their values with subscript syntax
- Define initializers to set up their initial state
- Be extended to add functionality beyond a default implementation
- Conform to protocols to provide standard functionality of a certain kind
Classes have additional capabilities that structures do not have:
- Inheritance lets one class inherit the characteristics of another.
- Type casting lets you check and interpret the type of a class instance at runtime.
- Deinitializers let an instance of a class free up any resources it has assigned.
- Reference counting allows more than one reference to a class instance.
Computed properties
A computed property calculates its value each time it is read. It can have only a getter, or a getter and a setter. The two declarations of vacationRemaining below are alternatives; a type can declare only one of them:
struct Employee { let name: String var vacationAllocated = 14 var vacationTaken = 0
// Getter only var vacationRemaining: Int { vacationAllocated - vacationTaken }}struct Employee { let name: String var vacationAllocated = 14 var vacationTaken = 0
// Getter and setter var vacationRemaining: Int { get { vacationAllocated - vacationTaken } set { vacationAllocated = vacationTaken + newValue } }}In the setter, newValue is the value being assigned.
Take action when a property changes
Property observers run code when a stored property changes: didSet runs right after the change, willSet runs right before it.
struct Game { var score = 0 { didSet { print("Score is now \(score)") } }}Swift provides the constant newValue inside willSet and the constant oldValue inside didSet:
struct App { var contacts = [String]() { willSet { print("Current value is: \(contacts)") print("New value will be: \(newValue)") }
didSet { print("There are now \(contacts.count) contacts.") print("Old value was \(oldValue)") } }}
var app = App()app.contacts.append("Adrian E")app.contacts.append("Allen W")app.contacts.append("Ish S")Initializers
For a struct, Swift generates a memberwise initializer from its stored properties. You can still write a custom initializer.
Swift does not generate a memberwise initializer for classes. You either write your own initializer or give every property a default value.
Inheritance
A subclass names its superclass after a colon. Its initializer sets its own properties first and then calls super.init. Use override to replace a method of the superclass:
class Employee { let hours: Int
init(hours: Int) { self.hours = hours }
func printSummary() { print("I work \(hours) hours a day.") }}
class Developer: Employee { let isPrincipal: Bool
init(hours: Int, isPrincipal: Bool) { self.isPrincipal = isPrincipal super.init(hours: hours) }
func work() { print("I'm writing code for \(hours) hours.") }
override func printSummary() { print("I'm a developer who will sometimes work \(hours) hours a day, but other times spend hours arguing about whether code should be indented using tabs or spaces.") }}
class Manager: Employee { func work() { print("I'm going to meetings for \(hours) hours.") }}Manager adds no stored properties, so it inherits the initializer of Employee.
Copy classes and structures
Classes are reference types: copies of a class instance point to the same data, so changing one copy changes all of them:
class User { var username = "Anonymous"}var user1 = User()var user2 = user1user2.username = "Taylor"print(user1.username) // Taylorprint(user2.username) // TaylorStructs are value types and do not share their data between copies. Changing class User to struct User gives a different result:
struct User { var username = "Anonymous"}var user1 = User()var user2 = user1user2.username = "Taylor"print(user1.username) // Anonymousprint(user2.username) // TaylorTo create an independent copy of a class instance (a deep copy), create a new instance and copy all the data across yourself:
class User { var username = "Anonymous"
func copy() -> User { let user = User() user.username = username return user }}Extensions
Extensions add new functionality to an existing class, structure, enumeration or protocol type. An extension can also make an existing type adopt one or more protocols:
extension SomeType: SomeProtocol, AnotherProtocol { // implementation of protocol requirements goes here}For example, given the Rect, Point and Size structures from the Swift book, an extension can add an initializer that takes a center point and a size:
extension Rect { init(center: Point, size: Size) { let originX = center.x - (size.width / 2) let originY = center.y - (size.height / 2) self.init(origin: Point(x: originX, y: originY), size: size) }}Protocols
Swift protocols are similar to Java interfaces. A protocol can require initializers, properties (read-only { get } or read-write { get set }), type members (static) and methods. A method that changes a value type must be marked mutating:
protocol SomeProtocol { init(someParameter: Int) // Initializer requirement var mustBeSettable: Int { get set } // Property requirement var doesNotNeedToBeSettable: Int { get } // Property requirement static func someTypeMethod() // Method requirement}
protocol AnotherProtocol { static var someTypeProperty: Int { get set } // Property requirement func random() -> Double // Method requirement mutating func toggle() // Mutating method requirement}
struct SomeStructure: SomeProtocol, AnotherProtocol { // structure definition goes here}
class SomeClass: SomeProtocol, AnotherProtocol { // A class must mark the initializer from SomeProtocol as `required` required init(someParameter: Int) { // initializer implementation goes here } // class definition goes here}The required modifier makes every subclass implement the initializer too, so subclasses still conform to the protocol.
Comparable
Comparable is the protocol that lets Swift decide whether one value should be sorted before another, for example in sorted() or with the < operator. Swift can synthesize Equatable for a struct whose properties are all Equatable, but it does not synthesize Comparable for structs. Implement a < function that takes two instances and returns true if the first one should be sorted before the second:
struct Location: Comparable { let name: String
static func <(lhs: Location, rhs: Location) -> Bool { lhs.name < rhs.name }}Comparable inherits from Equatable, so the struct is also Equatable. The operator can also be written as a top-level func <(lhs: Location, rhs: Location) -> Bool outside the type.
Optionals
An optional either holds a value or is nil. Its type is written with a question mark, such as Int?. You must unwrap it before using the value.
Unwrap optionals
if let runs its body only when the optional has a value. Writing if let number = number shadows the optional with a non-optional constant of the same name, available only inside the body. This is common with optionals, and since Swift 5.7 you can shorten it to if let number:
var number: Int? = nilif let number = number { // Runs only if number has a value print(number * number)}guard let handles the missing case first: its else block runs when the optional is nil and must exit the scope. After the guard, the unwrapped value is available for the rest of the function:
func printSquare(of number: Int?) { guard let number = number else { // Runs if number doesn't have a value print("Missing input") return } print("\(number) x \(number) is \(number * number)")}The nil-coalescing operator ?? provides a default value when the optional is empty. For dictionaries, the default: subscript does the same:
let captains = [ "Enterprise": "Picard", "Voyager": "Janeway", "Defiant": "Sisko"]let captain = captains["Serenity"] ?? "N/A"let otherCaptain = captains["Serenity", default: "N/A"]Optional chaining
Optional chaining (?.) calls properties and methods on an optional. If any link in the chain is nil, the whole expression is nil, which you can then replace with ??:
struct Book { let title: String let author: String?}
var book: Book? = nillet author = book?.author?.first?.uppercased() ?? "A"Here author is the uppercased first letter of the author’s name, or "A" if the book, the author or the first letter is missing.