Swift: reference

Apple's language: apps for iPhone, iPad and Mac, optionals, structs and protocols.

Program structure

Minimal program

In a main.swift file the code runs top to bottom without a separate main function. print prints a value and moves to a new line.

print("Hello, world!")

Entry point @main

In projects with several files the entry point is marked with the @main attribute on a type with a static main method.

@main
struct App {
    static func main() {
        print("Hello")
    }
}

Build and run

swiftc compiles a file, while swift package and swift run work with Swift Package Manager projects. The commands run in a terminal.

swiftc main.swift -o hello
./hello

swift package init --type executable
swift run

Variables and types

let and var

let is a constant and var is a variable. The type is inferred, and an explicit type is written after a colon.

let name = "Olena"
var score = 0
score += 10
let age: Int = 16
print(name, score, age)

Basic types

Main types: Int, Double, Float, Bool, Character, String. The tuple (1, "one") groups several values, accessed by number.

let i: Int = 42
let d: Double = 3.14
let f: Float = 2.5
let b: Bool = true
let c: Character = "a"
let s: String = "text"
let t = (1, "one")
print(t.0, t.1)

Type conversion

Types are not converted implicitly: write Double(x). Int("12") returns an optional because the string may not be a number.

let x = 7
let y = Double(x) / 2
let n = Int("12")
let m = Int("abc")
print(y, n ?? 0, m ?? -1)

Strings

Interpolation

An expression in \( ) is inserted into the string. Strings in Swift are values: they are copied on assignment.

let name = "Swift"
let a = 3
let b = 4
print("Hello, \(name)!")
print("Sum: \(a + b)")

String methods

The length is count, not length. hasPrefix and hasSuffix check the start and the end, and split splits a string into parts.

let s = "Hello, World"
print(s.count)
print(s.uppercased())
print(s.lowercased())
print(s.hasPrefix("Hello"))
print(s.contains("o"))
print("a,b,c".split(separator: ","))

Multiline strings

Triple quotes define text over several lines. The indentation of the closing quotes is removed from all lines.

let text = """
    Line one
    Line two
    """
print(text)

Conditions

if and the ternary operator

Parentheses around the condition are not needed, but curly braces are required. The condition must be a Bool; a number does not work.

let age = 16
if age < 12 {
    print("child")
} else if age < 18 {
    print("teen")
} else {
    print("adult")
}
let status = age >= 18 ? "adult" : "minor"

switch

switch must cover all values, so default is often needed. break is not needed: branches do not fall through.

let day = 6
switch day {
case 1...5:
    print("weekday")
case 6, 7:
    print("weekend")
default:
    print("unknown")
}

switch with tuples

Branches can destructure tuples, bind values with let and add a condition with where.

let point = (2, 0)
switch point {
case (0, 0):
    print("origin")
case (let x, 0):
    print("on x axis at \(x)")
case (_, let y) where y > 0:
    print("above")
default:
    print("other")
}

Loops

for-in

1...3 includes the right end, 0..<3 excludes it. stride sets the step.

for i in 1...3 { print(i) }
for i in 0..<3 { print(i) }
for ch in "abc" { print(ch) }
for i in stride(from: 0, to: 10, by: 2) { print(i) }

enumerated

enumerated gives pairs of index and element. If the loop variable is not needed, replace it with _.

let items = ["a", "b", "c"]
for item in items { print(item) }
for (i, v) in items.enumerated() {
    print(i, v)
}

while, repeat, continue

repeat-while checks the condition after the body, so it runs at least once. break and continue work as in other languages.

var n = 3
while n > 0 {
    print(n)
    n -= 1
}
repeat { n += 1 } while n < 3
for i in 1...10 {
    if i % 2 == 0 { continue }
    if i > 7 { break }
    print(i)
}

Functions

Declaration

The result is given after ->. A single-expression body can omit return. _ lets you call without an argument label.

func add(_ a: Int, _ b: Int) -> Int {
    return a + b
}
func square(_ x: Int) -> Int { x * x }
func hello() { print("hi") }

print(add(2, 3), square(4))

Argument labels

A parameter has an external label for the call (person) and an internal name (name). Default values let you skip arguments.

func greet(person name: String, greeting: String = "Hello") -> String {
    "\(greeting), \(name)!"
}

print(greet(person: "Olena"))
print(greet(person: "Olena", greeting: "Hi"))

Variadic and inout

Int... accepts any number of arguments. inout lets you change the passed variable, and the call adds &.

func sum(_ nums: Int...) -> Int {
    nums.reduce(0, +)
}
func inc(_ x: inout Int) { x += 1 }

var v = 1
inc(&v)
print(sum(1, 2, 3), v)

Tuple as a result

A function can return several values as a tuple, and its elements can be named. min() returns an optional because the array may be empty.

func minMax(_ a: [Int]) -> (min: Int, max: Int) {
    return (a.min() ?? 0, a.max() ?? 0)
}

let r = minMax([3, 1, 2])
print(r.min, r.max)

Closures

Closure and map, filter

Closures are written in curly braces, and parameters can be written as $0, $1. map transforms, filter selects, reduce folds.

let double = { (x: Int) -> Int in x * 2 }
print(double(5))

let nums = [1, 2, 3, 4]
print(nums.map { $0 * 2 })
print(nums.filter { $0 % 2 == 0 })
print(nums.reduce(0, +))
print(nums.sorted { $0 > $1 })

Function as a parameter

A function type is written as (Int) -> Int. The last function argument can follow the parentheses (a trailing closure).

func applyTwice(_ x: Int, _ f: (Int) -> Int) -> Int {
    f(f(x))
}

print(applyTwice(3) { $0 + 1 })
print(applyTwice(3, { $0 * 2 }))

Collections

Array

An array is mutable if declared with var. append adds an element and remove(at:) removes one by index.

var arr = [3, 1, 2]
arr.append(4)
arr.remove(at: 0)
print(arr, arr.count)
print(arr.sorted())
print(arr[0])

Dictionary and Set

Looking up a dictionary key returns an optional. Key order is not guaranteed, so keys are sorted. Set stores unique values.

var ages = ["Olena": 16, "Max": 17]
ages["Anna"] = 15
print(ages["Olena"] ?? 0)
print(ages["Zed"] ?? 0)
for key in ages.keys.sorted() { print(key, ages[key] ?? 0) }

var set: Set = [1, 2, 3]
set.insert(3)
set.insert(4)
print(set.count, set.contains(2))

Useful methods

allSatisfy checks all elements, contains looks for a matching one, joined joins strings. max() and first return optionals.

let nums = [5, 3, 8, 1]
print(nums.max() ?? 0)
print(nums.contains { $0 > 7 })
print(nums.allSatisfy { $0 > 0 })
print(nums.first ?? 0)
print(nums.map { String($0) }.joined(separator: ", "))

Structs, classes and enums

struct

A struct is a value type: it is copied on assignment. The memberwise initializer is generated automatically.

struct Point {
    var x: Int
    var y: Int
    func sum() -> Int { x + y }
}

var a = Point(x: 1, y: 2)
var b = a
b.x = 10
print(a.x, b.x, a.sum())

class

A class is a reference type: p and q point to the same object. The init initializer is written by hand, and self is the current object.

class Person {
    let name: String
    var age: Int
    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
}

let p = Person(name: "Olena", age: 16)
let q = p
q.age = 17
print(p.age)

enum with data

enum cases can carry data. In a switch they are unpacked with let, and the compiler checks that all cases are handled.

enum Shape {
    case circle(radius: Double)
    case rect(w: Double, h: Double)
}

let s = Shape.rect(w: 2, h: 3)
switch s {
case .circle(let r): print(r)
case .rect(let w, let h): print(w * h)
}

Protocols and extensions

Protocol

A protocol describes requirements for a type. Structs, classes and enums implement it, and any Animal is a value of any such type.

protocol Animal {
    var name: String { get }
    func sound() -> String
}

struct Dog: Animal {
    let name = "Rex"
    func sound() -> String { "Woof" }
}

let a: any Animal = Dog()
print(a.name, a.sound())

extension

extension adds methods and computed properties to an existing type, including a standard one, without inheritance.

extension Int {
    var isEven: Bool { self % 2 == 0 }
}

extension String {
    func shout() -> String { uppercased() + "!" }
}

print(4.isEven, "hi".shout())

Optionals

Optional and ??

A type with ? can hold nil. ?? gives a default value, ?. safely accesses a member, and if let unwraps the value.

var name: String? = nil
print(name ?? "unknown")
name = "Swift"
print(name?.count ?? 0)
if let n = name {
    print(n)
}

guard let

guard exits the function if the condition is false. The unwrapped value stays available afterwards, so the code has no extra nesting.

func show(_ age: Int?) {
    guard let age = age else {
        print("no age")
        return
    }
    print(age)
}

show(nil)
show(16)

Force unwrapping

The ! sign force-unwraps an optional, and for nil the program crashes. It is safer to use if let, guard or ??.

let text: String? = "abc"
print(text!.count)
print(text?.uppercased() ?? "")

Errors

throws and throw

Errors are values of types conforming to the Error protocol, usually an enum. A function that throws them is marked throws.

enum AgeError: Error {
    case negative
    case tooBig(Int)
}

func check(_ age: Int) throws -> Int {
    if age < 0 { throw AgeError.negative }
    if age > 150 { throw AgeError.tooBig(age) }
    return age
}

do, try, catch

A call to a throws function is marked with try inside do. catch blocks handle different errors, and the error variable is available implicitly.

enum E: Error { case bad }
func f(_ x: Int) throws -> Int {
    if x < 0 { throw E.bad }
    return x
}

do {
    print(try f(-1))
} catch E.bad {
    print("bad value")
} catch {
    print("other: \(error)")
}

try? and defer

try? turns an error into nil. The defer block runs when leaving the scope, even after return.

enum E: Error { case bad }
func f(_ x: Int) throws -> Int {
    if x < 0 { throw E.bad }
    return x
}

let v = try? f(-1)
print(v ?? 0)

func work() {
    defer { print("cleanup") }
    print("work")
}
work()

What is next

A lessons course for this language is on the way, and the reference is already available.

A course is on the way. For now only the reference is available; lessons and tasks will follow.