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
- Choose between an enum, a struct and a class, and justify the choice
- Predict the output of code that copies structs and shares class instances
- Use stored, computed, lazy, observed and static properties
- Write protocols with default implementations, and explain
someversusany - Write generic functions and types with constraints
- Throw, catch and convert errors with
do/catch,try?andtry!
Contents
- Enums
- Structs
- Classes and inheritance
- Value vs reference semantics
- Properties
- Access control
- Protocols and extensions
- Generics
- Equatable, Hashable, Comparable, Identifiable
- 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- Raw values are fixed values of one type (
String,Int,Double,Character), declared after the enum name. Stringraw values default to the case name.Intraw values start at 0 and count up from the previous case.init(rawValue:)returns an optional: the raw value might not match any case.CaseIterablegives youallCases, an array of every case in declaration order.
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 value | Associated value | |
|---|---|---|
| Declared | enum E: Int { case a = 1 } | case circle(radius: Double) |
| Same for every use of the case? | Yes: fixed at compile time | No: set when you create the value |
| Types | One type for all cases | Each case can differ |
| Read with | .rawValue | switch / if case let |
| Both in one enum? | No | No |
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.
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
greenStructs
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- Memberwise initializer: Swift generates
init(x:y:)from the stored properties, in order. Properties with a default value become optional arguments. - If you write your own
initinside the struct, the memberwise one disappears. Write it in anextensionto keep both. - A method that changes a stored property must be
mutating. - A
letstruct is fully immutable: you can't change any property or call a mutating method.
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")struct Point { var x = 0; var y = 0 }
let p = Point()
p.x = 5p is a let constant holding a value type, so none of its properties can change. Declare it with var.
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.
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
3overrideis required to replace a superclass method or property. Leaving it out is a compile error.super.method()calls the superclass version.finalon a class stops subclassing; on a method it stops overriding. It also lets the compiler call it directly (faster).ischecks a type;as?casts and returns an optional;as!casts or crashes.- Calling
sound()on anAnimalvariable runs theDogversion if the object is aDog: dynamic dispatch (polymorphism).
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| Kind | Rule |
|---|---|
Designated init | Initializes all of the class's own properties, then calls a designated super.init |
convenience init | Must call another initializer of the same class (self.init(...)) |
required init | Every subclass must implement it too (marked required again) |
Failable init? | Can return nil; the result is optional |
deinit | Runs just before the instance is freed. Classes only, no parameters, no parentheses |
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 outclass 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.
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 instanceOutput
1 99
99 99
true
false| struct / enum | class | |
|---|---|---|
| Semantics | Value: copied | Reference: shared |
| Inheritance | No (structs can adopt protocols) | Yes, single inheritance |
| Memberwise init | Yes (structs) | No |
deinit | No | Yes |
| Methods that change properties | Need mutating | No keyword needed |
let instance | Nothing can change | Reference fixed; var properties can still change |
Identity === | Not available | Yes |
| Thread safety | Copies are independent | Shared state needs care |
| Used for | Models, SwiftUI views, most data | Shared state, identity, @Observable models, UIKit |
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 0Properties
| Kind | What it is | Example |
|---|---|---|
| Stored | Stores a value in the instance | var name: String |
| Computed | Calculates a value each time; stores nothing; always var | var area: Double { w * h } |
| Lazy | Stored, but set the first time it's read; must be var | lazy var cache = load() |
| Observed | Stored, with willSet/didSet code | var score = 0 { didSet { ... } } |
Type (static) | One value shared by the type, not per instance | static 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 falseProperty 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
30willSetruns before the change; the new value isnewValue.didSetruns after; the old value isoldValue.- Observers don't run when the property is set inside the type's own initializer.
- Assigning the property inside its own
didSet(for example to clamp it) does not call the observers again. - A computed property can't have observers: put the code in its setter.
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
60Access control
Access levels say which code can see a declaration. From most open to most restricted:
| Level | Visible to | Subclass / override outside the module? |
|---|---|---|
open | Any module | Yes (classes and members only) |
public | Any module | No |
internal (default) | The same module (app or framework) | n/a |
fileprivate | The same source file | n/a |
private | The enclosing declaration, plus its extensions in the same file | n/a |
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 levelProtocols 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.0protocol 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: Rainprotocol 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 Byesome vs any
some Shape (opaque type) | any Shape (existential) | |
|---|---|---|
| Meaning | One specific type that conforms; the compiler knows which, the caller doesn't | A box that can hold any conforming type, and a different one each time |
| Mixed types in one array? | No | Yes: [any Shape] |
| Return different types from one function? | No: every return must be the same type | Yes |
| Speed | Static dispatch, no boxing | Boxed, dynamic dispatch: a little slower |
| Typical use | var body: some View, func make() -> some Shape | Heterogeneous 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.0func 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!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
truefunc 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
11where 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| Syntax | Meaning |
|---|---|
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: Hashable | Same constraint, written as a where clause |
func f(_ x: some Comparable) | Shorthand for a generic parameter (Swift 5.7+) |
extension Stack where Element == Int | Members only for one specialization |
Equatable, Hashable, Comparable, Identifiable
| Protocol | Gives you | You implement | Synthesized automatically? |
|---|---|---|---|
Equatable | == and != | static func == | Structs whose properties are all Equatable; enums whose associated values are Equatable (enums with no associated values always) |
Hashable | Use as a Set element or Dictionary key | hash(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+) |
Identifiable | A stable identity: var id | var id: ID where ID: Hashable | No |
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 smallstruct 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
invalidAmounttry, try? and try!
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| Form | On success | On error |
|---|---|---|
try (inside do/catch or a throwing function) | The value | Jumps to catch / propagates to the caller |
try? | The value wrapped in an optional | nil; the error is discarded |
try! | The value | Crash |
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
cleanuprethrows: the function only throws if the closure you pass throws.mapandfilterare declared this way.deferruns when the current scope ends, on every path (return, throw or falling off the end). Use it for clean-up.- Swift 6 adds typed throws:
func f() throws(BankError)tells callers the exact error type. - Swift errors are not exceptions: no stack unwinding cost, and every throwing call is visible because of
try.
Exam traps
| Code or claim | What really happens |
|---|---|
Direction(rawValue: "x") | nil: the init returns an optional |
enum E: Int { case a = 1, b, c }: E.c.rawValue | 3 |
String raw value with no explicit value | The case name: case north gives "north" |
| switch on an enum without every case | Compile error, unless there's a default |
| Struct method that assigns a property | Needs mutating |
Mutating a let struct | Compile error, even for var properties |
Changing a var property of a let class instance | Allowed: the reference is constant, not the object |
var b = a where a is a struct, then change b | a is unchanged (copy) |
let b = a where a is a class instance, then change b.x | a.x changes too (shared) |
=== on structs | Compile error: identity is for class instances only |
Class with an uninitialized var and no init | Compile error: classes get no memberwise init |
Missing override | Compile error |
Subclassing a final class | Compile error |
didSet during the type's own init | Doesn't run |
lazy let | Compile error: lazy must be var |
| Stored property in an extension | Compile error: only computed properties |
| Default access level | internal, not private |
func f() -> some P returning two different types | Compile error: use any P |
== on a struct without Equatable | Compile error: conformance must be declared |
try? on a call that throws | nil; 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
What does this print?
Show the answer
3
Int raw values count up from the previous case: 1, 2, 3.
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.
Which keyword lets a struct method change its own properties?
Show the answer
mutating
What does this print?
Show the answer
0
Structs are copied on assignment.
What does this print?
Show the answer
5
Both constants refer to the same instance;
letfixes the reference, not the object.Which operator checks whether two variables refer to the same class instance?
Show the answer
===
Which of these can a struct NOT do?
Show the answer
Inherit from another struct
Which property kind stores nothing and calculates its value on every read?
Show the answer
computed
Inside
didSet, what is the previous value called?Show the answer
oldValue
What is the default access level in Swift?
Show the answer
internal
Which access level allows subclassing from another module?
Show the answer
open
publicclasses can be used but not subclassed outside their module.What does
var body: some Viewmean?Show the answer
body returns one specific View type the compiler knows, hidden from callers
someis an opaque type: one fixed underlying type.Which can an extension NOT add?
Show the answer
A stored property
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
What does this print?
Show the answer
-1
try?turns the error intonil, then??supplies -1.What happens when a
try!call throws?Show the answer
The program crashes
Which protocol must
ForEach(items) { ... }elements conform to when noid:is passed?Show the answer
Identifiable
For which type does Swift synthesize
Comparableautomatically?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.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.