ViewLab

Swift & SwiftUI course › Session 2

Custom types and object-oriented Swift

How Swift models data: enums, structs and classes, value versus reference semantics, protocols, generics and error handling. Every SwiftUI view and model you write later is built from these.

About 30 minutes · covers Enums, structs, classes, properties, protocols, extensions, generics, Identifiable, Hashable, errors

Open the interactive lesson (live previews, quizzes) →

What you'll learn

Contents

  1. Enums
  2. Structs
  3. Classes and inheritance
  4. Value vs reference semantics
  5. Properties
  6. Access control
  7. Protocols and extensions
  8. Generics
  9. Equatable, Hashable, Comparable, Identifiable
  10. Error handling

Enums

An enum defines a type with a fixed set of cases. A value of the type is always exactly one of them. Swift enums are full types: they can have raw values, associated values, methods and computed properties.

enum Direction: String, CaseIterable {
    case north, south = "S", east, west
}
let heading = Direction.north
print(heading, heading.rawValue)
print(Direction.south.rawValue, Direction.east.rawValue)
print(Direction.allCases.count)

enum Planet: Int {
    case mercury = 1, venus, earth
}
print(Planet.earth.rawValue)
print(Planet(rawValue: 2) == .venus, Planet(rawValue: 9) == nil)

Output

north north
S east
4
3
true true
This doesn't compile
enum Planet: Int { case mercury = 1, venus, earth }
let p: Planet = Planet(rawValue: 3)

Planet(rawValue:) returns Planet?. Unwrap it with if let, guard let or !.

Associated values

An associated value is data stored with one particular case. Each case can carry different types. You read the values with switch (or if case).

enum Shape {
    case circle(radius: Double)
    case rectangle(width: Double, height: Double)
    case point

    var area: Double {
        switch self {
        case .circle(let r): return 3.0 * r * r
        case let .rectangle(w, h): return w * h
        case .point: return 0
        }
    }

    func describe() -> String {
        "area \(area)"
    }
}
let s = Shape.circle(radius: 2.0)
print(s)
print(s.area, Shape.rectangle(width: 2, height: 5).describe())
if case .circle(let r) = s {
    print("radius", r)
}

Output

circle(radius: 2.0)
12.0 area 10.0
radius 2.0
Raw valueAssociated value
Declaredenum E: Int { case a = 1 }case circle(radius: Double)
Same for every use of the case?Yes: fixed at compile timeNo: set when you create the value
TypesOne type for all casesEach case can differ
Read with.rawValueswitch / if case let
Both in one enum?NoNo
This doesn't compile
enum Light { case red, amber, green }
let light = Light.red
switch light {
case .red: print("stop")
case .green: print("go")
}

The switch isn't exhaustive: .amber is missing. Swift checks every enum switch, which is why adding a case later shows you every place to update.

Methods that change self

Enums and structs are value types, so a method that changes self must be marked mutating.

What does this print?
enum Light {
    case red, green, amber
    mutating func next() {
        switch self {
        case .red: self = .green
        case .green: self = .amber
        case .amber: self = .red
        }
    }
}
var light = Light.amber
light.next()
light.next()
print(light)
Show the answer
green

Try “Enums” with live code →

Structs

A struct groups related values and behaviour into one type. Structs are value types: assigning or passing one makes a copy. Int, String, Array and every SwiftUI view are structs.

struct Point {
    var x: Int
    var y: Int

    mutating func move(by d: Int) {
        x += d
        y += d
    }
    func distanceFromOrigin() -> Int {
        abs(x) + abs(y)
    }
}
var p = Point(x: 1, y: 2)      // memberwise initializer, generated for you
p.move(by: 3)
print(p)
print(p.distanceFromOrigin())

var q = p                      // a copy
q.x = 100
print(p.x, q.x)

Output

Point(x: 4, y: 5)
9
4 100
struct Settings {
    var volume = 5
    var theme = "Light"
}
print(Settings())
print(Settings(volume: 8))
print(Settings(volume: 2, theme: "Dark"))

Output

Settings(volume: 5, theme: "Light")
Settings(volume: 8, theme: "Light")
Settings(volume: 2, theme: "Dark")
This doesn't compile
struct Point { var x = 0; var y = 0 }
let p = Point()
p.x = 5

p is a let constant holding a value type, so none of its properties can change. Declare it with var.

This doesn't compile
struct Counter {
    var count = 0
    mutating func increment() { count += 1 }
}
let c = Counter()
c.increment()

A mutating method changes the value, so it can't be called on a let constant.

Try “Structs” with live code →

Classes and inheritance

A class is a reference type: variables hold a reference to one shared instance. Classes can inherit from one superclass, and Swift frees an instance when no references to it remain (ARC, automatic reference counting). Classes get no memberwise initializer: every stored property needs a default value or must be set in an init.

class Animal {
    let name: String
    init(name: String) {
        self.name = name
    }
    func sound() -> String { "..." }
    func describe() -> String { "\(name) says \(sound())" }
}

class Dog: Animal {
    var tricks: Int
    init(name: String, tricks: Int) {
        self.tricks = tricks           // 1. set this class's own properties
        super.init(name: name)         // 2. then call the superclass init
    }
    override func sound() -> String { "Woof" }
    override func describe() -> String {
        super.describe() + " and knows \(tricks) tricks"
    }
}

let pets: [Animal] = [Dog(name: "Bruno", tricks: 3), Animal(name: "Generic")]
for pet in pets {
    print(pet.describe())
}
print(pets[0] is Dog, pets[1] is Dog)
if let dog = pets[0] as? Dog {
    print(dog.tricks)
}

Output

Bruno says Woof and knows 3 tricks
Generic says ...
true false
3
Both are compile errors in Swift.
class Animal {
    func sound() -> String { "..." }
}
class Dog: Animal {
    func sound() -> String { "Woof" }   // error: overriding declaration requires an 'override' keyword
}

final class Wallet {}
class SmartWallet: Wallet {}            // error: inheritance from a final class 'Wallet'

Initializers: designated, convenience, required

class Vehicle {
    var wheels: Int
    init(wheels: Int) {                 // designated: sets every property
        self.wheels = wheels
    }
    convenience init() {                // convenience: must call another init of the same class
        self.init(wheels: 4)
    }
}
class Bike: Vehicle {
    init() {
        super.init(wheels: 2)
    }
}
print(Vehicle().wheels, Vehicle(wheels: 6).wheels, Bike().wheels)

Output

4 6 2
KindRule
Designated initInitializes all of the class's own properties, then calls a designated super.init
convenience initMust call another initializer of the same class (self.init(...))
required initEvery subclass must implement it too (marked required again)
Failable init?Can return nil; the result is optional
deinitRuns just before the instance is freed. Classes only, no parameters, no parentheses
deinit runs when the last strong reference disappears. Structs and enums have no deinit.
class Session {
    let user: String
    init(user: String) {
        self.user = user
        print("\(user) logged in")
    }
    deinit {
        print("\(user) logged out")
    }
}

var session: Session? = Session(user: "Asha")   // Asha logged in
session = nil                                   // last reference gone: Asha logged out
This doesn't compile
class Person {
    var name: String
    init(name: String) { self.name = name }
}
let p = Person()

Once a class defines an init(name:), there's no Person() initializer. Classes also never get a memberwise initializer.

Try “Classes and inheritance” with live code →

Value vs reference semantics

This is the most asked question in this session. A value type (struct, enum, tuple) is copied on assignment, so each variable has its own data. A reference type (class) is shared, so a change through one variable is visible through every other variable that refers to the same instance.

struct PointS { var x: Int }
class PointC {
    var x: Int
    init(x: Int) { self.x = x }
}

var s1 = PointS(x: 1)
var s2 = s1
s2.x = 99
print(s1.x, s2.x)

let c1 = PointC(x: 1)
let c2 = c1                 // same instance, two references
c2.x = 99                   // allowed: c2 is a constant reference, not a constant object
print(c1.x, c2.x)

print(c1 === c2)            // identity: same instance?
let c3 = PointC(x: 99)
print(c1 === c3)            // same values, different instance

Output

1 99
99 99
true
false
struct / enumclass
SemanticsValue: copiedReference: shared
InheritanceNo (structs can adopt protocols)Yes, single inheritance
Memberwise initYes (structs)No
deinitNoYes
Methods that change propertiesNeed mutatingNo keyword needed
let instanceNothing can changeReference fixed; var properties can still change
Identity ===Not availableYes
Thread safetyCopies are independentShared state needs care
Used forModels, SwiftUI views, most dataShared state, identity, @Observable models, UIKit
What does this print?
class Box { var value = 0 }
struct Card { var value = 0 }

let box = Box()
var boxes = [box, box]
boxes[0].value = 5

var card = Card()
var cards = [card, card]
cards[0].value = 5

print(box.value, boxes[1].value, card.value, cards[1].value)
Show the answer
5 5 0 0

Try “Value vs reference semantics” with live code →

Properties

KindWhat it isExample
StoredStores a value in the instancevar name: String
ComputedCalculates a value each time; stores nothing; always varvar area: Double { w * h }
LazyStored, but set the first time it's read; must be varlazy var cache = load()
ObservedStored, with willSet/didSet codevar score = 0 { didSet { ... } }
Type (static)One value shared by the type, not per instancestatic let maxUsers = 10
struct Temperature {
    var celsius: Double
    var fahrenheit: Double {               // computed, with get and set
        get { celsius * 9 / 5 + 32 }
        set { celsius = (newValue - 32) * 5 / 9 }
    }
    var isHot: Bool { celsius > 30 }       // read-only computed
}
var t = Temperature(celsius: 100)
print(t.fahrenheit, t.isHot)
t.fahrenheit = 32
print(t.celsius, t.isHot)

Output

212.0 true
0.0 false

Property observers

struct Account {
    var balance = 0 {
        willSet { print("will change \(balance) -> \(newValue)") }
        didSet { print("changed \(oldValue) -> \(balance)") }
    }
}
var account = Account()
account.balance = 50
account.balance -= 20
print(account.balance)

Output

will change 0 -> 50
changed 0 -> 50
will change 50 -> 30
changed 50 -> 30
30

Lazy and static

struct Report {
    static var created = 0             // shared by every Report
    static let title = "Monthly"
    let rows: [Int]
    lazy var total: Int = {
        print("computing total")
        return rows.reduce(0, +)
    }()
    init(rows: [Int]) {
        self.rows = rows
        Report.created += 1
    }
}
var r = Report(rows: [10, 20, 30])
_ = Report(rows: [])
print("made", Report.created, Report.title)
print(r.total)
print(r.total)

Output

made 2 Monthly
computing total
60
60

Try “Properties” with live code →

Access control

Access levels say which code can see a declaration. From most open to most restricted:

LevelVisible toSubclass / override outside the module?
openAny moduleYes (classes and members only)
publicAny moduleNo
internal (default)The same module (app or framework)n/a
fileprivateThe same source filen/a
privateThe enclosing declaration, plus its extensions in the same filen/a
private(set): public getter, private setter. This is encapsulation.
struct BankAccount {
    let owner: String
    private(set) var balance = 0          // anyone can read; only this type can write
    private var pin = "1234"               // hidden completely

    mutating func deposit(_ amount: Int) {
        guard amount > 0 else { return }
        balance += amount
    }
}

var account = BankAccount(owner: "Ravi")
account.deposit(100)
print(account.balance)      // 100
account.balance = 1_000_000 // error: cannot assign to property: 'balance' setter is inaccessible
print(account.pin)          // error: 'pin' is inaccessible due to 'private' protection level

Try “Access control” with live code →

Protocols and extensions

A protocol is a contract: a list of properties and methods a type must provide. A type conforms by listing the protocol and implementing the requirements. Structs, enums and classes can all conform, and a type can conform to many protocols (unlike single class inheritance).

protocol Shape {
    var name: String { get }          // read-only requirement (a let or var satisfies it)
    func area() -> Double
}

struct Square: Shape {
    let side: Double
    var name: String { "Square" }
    func area() -> Double { side * side }
}
struct Circle: Shape {
    let radius: Double
    let name = "Circle"
    func area() -> Double { 3.0 * radius * radius }
}

let shapes: [any Shape] = [Square(side: 2), Circle(radius: 1)]   // protocol as a type
for s in shapes {
    print(s.name, s.area())
}
print(shapes.reduce(0.0) { $0 + $1.area() })

Output

Square 4.0
Circle 3.0
7.0
This doesn't compile
protocol Shape {
    var name: String { get }
    func area() -> Double
}
struct Triangle: Shape {
    func area() -> Double { 0 }
}

Triangle doesn't provide name, so it doesn't conform to Shape.

Protocol extensions: default implementations

protocol Describable {
    var title: String { get }
    func describe() -> String
}
extension Describable {
    func describe() -> String { "Item: \(title)" }     // default implementation
}
struct Book: Describable { let title: String }           // uses the default
struct Song: Describable {
    let title: String
    func describe() -> String { "Song: \(title)" }      // replaces it
}
print(Book(title: "Swift").describe())
print(Song(title: "Rain").describe())

Output

Item: Swift
Song: Rain
Classic trap: a method declared only in a protocol extension is chosen by the variable's static type, not the real object.
protocol Greeter {
    func hello() -> String            // a requirement
}
extension Greeter {
    func hello() -> String { "default hello" }
    func bye() -> String { "default bye" }   // NOT a requirement: extension only
}
struct English: Greeter {
    func hello() -> String { "Hello" }
    func bye() -> String { "Bye" }
}

let g: any Greeter = English()
print(g.hello(), g.bye())      // Hello default bye
let e = English()
print(e.hello(), e.bye())      // Hello Bye

some vs any

some Shape (opaque type)any Shape (existential)
MeaningOne specific type that conforms; the compiler knows which, the caller doesn'tA box that can hold any conforming type, and a different one each time
Mixed types in one array?NoYes: [any Shape]
Return different types from one function?No: every return must be the same typeYes
SpeedStatic dispatch, no boxingBoxed, dynamic dispatch: a little slower
Typical usevar body: some View, func make() -> some ShapeHeterogeneous collections, stored properties of protocol type
protocol Shape { func area() -> Double }
struct Square: Shape { let side: Double; func area() -> Double { side * side } }

func makeShape() -> some Shape { Square(side: 3) }      // caller sees "some Shape"
func total(_ items: [any Shape]) -> Double { items.reduce(0.0) { $0 + $1.area() } }
func printArea(_ s: some Shape) { print(s.area()) }     // same as a generic <T: Shape>

printArea(makeShape())
print(total([Square(side: 1), makeShape()]))

Output

9.0
10.0
some = one hidden type. Use any Shape (or a single enum) when you must return different types.
func makeShape(round: Bool) -> some Shape {
    if round { return Circle(radius: 1) }
    return Square(side: 2)
    // error: function declares an opaque return type 'some Shape', but the return
    // statements in its body do not have matching underlying types
}

Extensions

An extension adds methods, computed properties, initializers, nested types and protocol conformances to an existing type, even one you don't own like Int. Extensions can't add stored properties or override existing methods.

extension Int {
    var isEven: Bool { self % 2 == 0 }
    func times(_ action: () -> Void) {
        for _ in 0..<self { action() }
    }
}
extension String {
    func shout() -> String { self.uppercased() + "!" }
}
print(4.isEven, 7.isEven)
2.times { print("hi") }
print("swift".shout())

Output

true false
hi
hi
SWIFT!

Try “Protocols and extensions” with live code →

Generics

Generics let you write one function or type that works with any type, while keeping full type safety. The placeholder (T, Element) is replaced by a real type at each use. Array<Element>, Dictionary<Key, Value> and Optional<Wrapped> are all generic.

func swapValues<T>(_ a: inout T, _ b: inout T) {
    let temp = a
    a = b
    b = temp
}
var x = 1, y = 2
swapValues(&x, &y)
print(x, y)
var first = "A", second = "B"
swapValues(&first, &second)
print(first, second)

func largest<T: Comparable>(_ items: [T]) -> T? {       // constraint: T must be Comparable
    guard var best = items.first else { return nil }
    for item in items where item > best { best = item }
    return best
}
print(largest([3, 9, 2])!, largest(["kiwi", "apple", "mango"])!)
print(largest([Int]()) == nil)

Output

2 1
B A
9 mango
true
Without the constraint T: Comparable, Swift doesn't know that T supports >.
func largest<T>(_ a: T, _ b: T) -> T {
    a > b ? a : b      // error: binary operator '>' cannot be applied to two 'T' operands
}

Generic types

struct Stack<Element> {
    private var items: [Element] = []
    mutating func push(_ item: Element) { items.append(item) }
    mutating func pop() -> Element? { items.popLast() }
    var top: Element? { items.last }
    var count: Int { items.count }
}

var numbers = Stack<Int>()
numbers.push(1)
numbers.push(2)
print(numbers.pop()!, numbers.top!, numbers.count)

var words = Stack<String>()
words.push("swift")
print(words.top!)

extension Stack where Element == Int {           // only for Stack<Int>
    var sum: Int { items.reduce(0, +) }
}
numbers.push(10)
print(numbers.sum)

Output

2 1 1
swift
11

where clauses

func allSame<C: Collection>(_ items: C) -> Bool where C.Element: Equatable {
    guard let first = items.first else { return true }
    return items.allSatisfy { $0 == first }
}
print(allSame([1, 1, 1]), allSame(["a", "b"]), allSame([Int]()))

Output

true false true
SyntaxMeaning
func f<T>(_ x: T)Any type
func f<T: Comparable>(_ x: T)T must conform to Comparable
func f<T>(_ x: T) where T: HashableSame constraint, written as a where clause
func f(_ x: some Comparable)Shorthand for a generic parameter (Swift 5.7+)
extension Stack where Element == IntMembers only for one specialization

Try “Generics” with live code →

Equatable, Hashable, Comparable, Identifiable

ProtocolGives youYou implementSynthesized automatically?
Equatable== and !=static func ==Structs whose properties are all Equatable; enums whose associated values are Equatable (enums with no associated values always)
HashableUse as a Set element or Dictionary keyhash(into:)Same rules as Equatable. Hashable implies Equatable
Comparable<, >, <=, >=, sorted(), min(), max()static func <Enums without raw values, if any associated values are Comparable (Swift 5.3+)
IdentifiableA stable identity: var idvar id: ID where ID: HashableNo
struct Point: Hashable {                    // Equatable and Hashable synthesized
    var x: Int
    var y: Int
}
print(Point(x: 1, y: 2) == Point(x: 1, y: 2))
let unique: Set<Point> = [Point(x: 1, y: 2), Point(x: 1, y: 2), Point(x: 0, y: 0)]
print(unique.count)

struct Version: Comparable {
    let major: Int
    let minor: Int
    static func < (a: Version, b: Version) -> Bool {
        (a.major, a.minor) < (b.major, b.minor)
    }
}
let versions = [Version(major: 2, minor: 0), Version(major: 1, minor: 10), Version(major: 1, minor: 2)]
print(versions.sorted().map { "\($0.major).\($0.minor)" })
print(versions.max()! == Version(major: 2, minor: 0))

enum Size: Comparable { case small, medium, large }
print(Size.small < .large, [Size.large, .small].min()!)

Output

true
2
["1.2", "1.10", "2.0"]
true
true small
Nothing is synthesized until you declare the conformance: struct Cat: Hashable.
struct Cat { var name: String }
print(Cat(name: "Tom") == Cat(name: "Tom"))
// error: binary operator '==' cannot be applied to two 'Cat' operands

let cats: Set<Cat> = []
// error: generic struct 'Set' requires that 'Cat' conform to 'Hashable'

Identifiable, and why SwiftUI needs it

Identifiable requires one property, id, whose type is Hashable. SwiftUI's List and ForEach must know which row is which between updates, so they can animate inserts and deletes and keep each row's state. They get that identity either from Identifiable or from a key path you pass, such as id: \.self (which needs the elements to be Hashable).

struct Todo: Identifiable {
    let id: Int              // stable and unique: not the array index
    var title: String
    var done = false
}
var tasks = [Todo(id: 1, title: "Read"), Todo(id: 2, title: "Code"), Todo(id: 3, title: "Sleep")]
tasks.remove(at: 0)
print(tasks.map { $0.id })            // identities survive the delete; indexes shifted

func ids<T: Identifiable>(_ items: [T]) -> [T.ID] {
    items.map { $0.id }
}
print(ids(tasks))

enum Tab: String, CaseIterable, Identifiable {
    case home, search, profile
    var id: String { rawValue }       // enums often use rawValue as id
}
print(Tab.allCases.map { $0.id })

Output

[2, 3]
[2, 3]
["home", "search", "profile"]

Try “Equatable, Hashable, Comparable, Identifiable” with live code →

Error handling

A function marked throws can throw an error instead of returning. Errors are values of a type that conforms to Error, usually an enum. The caller must mark every throwing call with try and handle the error, or be throws itself.

enum BankError: Error {
    case invalidAmount
    case insufficientFunds(needed: Int)
}

func withdraw(_ amount: Int, from balance: Int) throws -> Int {
    guard amount > 0 else { throw BankError.invalidAmount }
    guard amount <= balance else {
        throw BankError.insufficientFunds(needed: amount - balance)
    }
    return balance - amount
}

do {
    print(try withdraw(30, from: 100))
    print(try withdraw(150, from: 100))
    print("never printed")
} catch BankError.insufficientFunds(let needed) {
    print("Short by", needed)
} catch {
    print("Other error:", error)          // 'error' is available automatically
}

do {
    _ = try withdraw(0, from: 10)
} catch {
    print(error)
}

Output

70
Short by 50
invalidAmount

try, try? and try!

What does this print?
enum BankError: Error { case invalidAmount }
func withdraw(_ amount: Int, from balance: Int) throws -> Int {
    guard amount > 0 else { throw BankError.invalidAmount }
    return balance - amount
}
print(try? withdraw(5, from: 10))
print(try? withdraw(-5, from: 10))
print(try! withdraw(5, from: 10))
Show the answer
Optional(5)
nil
5
FormOn successOn error
try (inside do/catch or a throwing function)The valueJumps to catch / propagates to the caller
try?The value wrapped in an optionalnil; the error is discarded
try!The valueCrash
This doesn't compile
enum BankError: Error { case invalidAmount }
func withdraw(_ amount: Int) throws -> Int {
    throw BankError.invalidAmount
}
let left = withdraw(5)

A call to a throwing function must be marked with try. Swift reports this at compile time (the Playground reports it when the error is thrown).

rethrows and defer

func applyTwice(_ value: Int, _ f: (Int) throws -> Int) rethrows -> Int {
    try f(try f(value))
}
print(applyTwice(3) { $0 * 2 })       // a non-throwing closure: no try needed

func process() {
    defer { print("cleanup") }        // runs when the scope exits, however it exits
    print("working")
}
process()

Output

12
working
cleanup

Try “Error handling” with live code →

Exam traps

Code or claimWhat really happens
Direction(rawValue: "x")nil: the init returns an optional
enum E: Int { case a = 1, b, c }: E.c.rawValue3
String raw value with no explicit valueThe case name: case north gives "north"
switch on an enum without every caseCompile error, unless there's a default
Struct method that assigns a propertyNeeds mutating
Mutating a let structCompile error, even for var properties
Changing a var property of a let class instanceAllowed: the reference is constant, not the object
var b = a where a is a struct, then change ba is unchanged (copy)
let b = a where a is a class instance, then change b.xa.x changes too (shared)
=== on structsCompile error: identity is for class instances only
Class with an uninitialized var and no initCompile error: classes get no memberwise init
Missing overrideCompile error
Subclassing a final classCompile error
didSet during the type's own initDoesn't run
lazy letCompile error: lazy must be var
Stored property in an extensionCompile error: only computed properties
Default access levelinternal, not private
func f() -> some P returning two different typesCompile error: use any P
== on a struct without EquatableCompile error: conformance must be declared
try? on a call that throwsnil; try! would crash

Viva questions and answers

Struct or class: which do you choose and why?

Struct by default: value semantics make data predictable and thread-friendly. Use a class when you need shared identity, inheritance, deinit, or an observable shared model.

What is the difference between value and reference types?

A value type is copied when assigned or passed, so each copy changes independently. A reference type is shared: all variables point to one instance, so a change is visible through all of them.

What is the difference between == and ===?

== compares values and requires Equatable. === checks whether two references point to the same class instance.

Raw values vs associated values?

Raw values are fixed constants of one type for each case, read with rawValue. Associated values are data attached when you create a case value, and they can differ per case and per instance.

Why do struct methods need mutating?

A struct's self is immutable inside methods by default. mutating says the method changes the value, so Swift only allows calling it on a var.

What is a computed property?

A property that stores nothing; it runs a getter (and optionally a setter) every time it's accessed. It must be declared with var.

What are property observers?

willSet and didSet blocks that run before and after a stored property changes. They don't run during the type's own initializer.

What is a lazy property?

A stored var whose initial value is computed the first time it's read. Useful for expensive setup that may never be needed.

What is a protocol?

A contract of required properties and methods. Any struct, enum or class can conform, and a type can conform to many protocols.

What is protocol-oriented programming?

Designing with protocols and protocol extensions (default implementations) instead of class hierarchies. It works with value types and allows multiple conformances.

Explain some vs any.

some P is an opaque type: one concrete type, hidden from the caller but known to the compiler. any P is an existential box that can hold different conforming types at runtime, at a small performance cost.

What are generics?

Code written with type placeholders, like func largest<T: Comparable>(_ items: [T]), that works with any type meeting the constraints while staying type-safe.

What can extensions do?

Add methods, computed properties, initializers, nested types and protocol conformances to any type, even ones you don't own. They can't add stored properties or override.

What is the difference between open and public?

Both are visible outside the module. Only open classes and members can be subclassed or overridden outside the module.

Why does SwiftUI's List need Identifiable?

It needs a stable id for each element to tell which rows were inserted, removed or moved, so it can animate changes and keep each row's state.

Explain try, try? and try!.

try propagates the error to a catch or the caller. try? converts an error into nil. try! asserts no error will happen and crashes if one does.

What is ARC?

Automatic Reference Counting: Swift counts strong references to each class instance and frees it, running deinit, when the count reaches zero.

What is the difference between a designated and a convenience initializer?

A designated init fully initializes the class and calls the superclass init. A convenience init must call another initializer of the same class.

Quiz

  1. What does this print?

    Show the answer

    3

    Int raw values count up from the previous case: 1, 2, 3.

  2. What is the type of Day(rawValue: 2)?

    Show the answer

    Day?

    The raw value might not match a case, so the initializer is failable.

  3. Which keyword lets a struct method change its own properties?

    Show the answer

    mutating

  4. What does this print?

    Show the answer

    0

    Structs are copied on assignment.

  5. What does this print?

    Show the answer

    5

    Both constants refer to the same instance; let fixes the reference, not the object.

  6. Which operator checks whether two variables refer to the same class instance?

    Show the answer

    ===

  7. Which of these can a struct NOT do?

    Show the answer

    Inherit from another struct

  8. Which property kind stores nothing and calculates its value on every read?

    Show the answer

    computed

  9. Inside didSet, what is the previous value called?

    Show the answer

    oldValue

  10. What is the default access level in Swift?

    Show the answer

    internal

  11. Which access level allows subclassing from another module?

    Show the answer

    open

    public classes can be used but not subclassed outside their module.

  12. What does var body: some View mean?

    Show the answer

    body returns one specific View type the compiler knows, hidden from callers

    some is an opaque type: one fixed underlying type.

  13. Which can an extension NOT add?

    Show the answer

    A stored property

  14. Why does func big<T>(_ a: T, _ b: T) -> T { a > b ? a : b } fail to compile?

    Show the answer

    T isn't constrained to Comparable

  15. What does this print?

    Show the answer

    -1

    try? turns the error into nil, then ?? supplies -1.

  16. What happens when a try! call throws?

    Show the answer

    The program crashes

  17. Which protocol must ForEach(items) { ... } elements conform to when no id: is passed?

    Show the answer

    Identifiable

  18. For which type does Swift synthesize Comparable automatically?

    Show the answer

    Enums without raw values or associated values

    Since Swift 5.3, simple enums compare by declaration order. Structs need a < you write.

  19. In a subclass init, what is the correct order?

    Show the answer

    Own properties first, then super.init

    Phase 1 of two-phase initialization: initialize your own stored properties, then delegate up.

← Swift fundamentals · SwiftUI fundamentals →

Practise this lesson interactively →