struct vs class in swift
TRANSCRIPT
STRUCT vs CLASS
Laurentiu Ungur, iOS Developer @P3-Digital Services
Why I should use a struct instead of a class ?
1. POWERFUL
PROBLEM WITH SUBCLASSING ?
struct Vehicle {let model: Stringlet price: Double
}
enum VehicleType {case car(licensePlate: String)case bicycle(chainRings: Int)
}
struct Vehicle {let model: Stringlet price: Double
let type: VehicleType }
let car = Vehicle(model: “X”, price: 200, type: .car(licensePlate: “CJ”))
let bicycle = Vehicle(model: “A”, price: 10, type: .bicycle(chainRings: 100))
2. VALUE SEMANTICS
3. AUTOMATIC INITIALIZER
struct Car {let brand: Stringlet model: Stringlet price: Double
}
struct Car {let brand: Stringlet model: Stringlet price: Double
init(brand: String, model: String, price: Double) {self.brand = brandself.model = modelself.price = price
}}
let myCar = Car(brand: “Tesla”, model: “S”, price: 100)
struct Car {let brand: Stringlet model: Stringlet price: Double
}
let myCar = Car(brand: “Tesla”, model: “S”, price: 100)
4. SPEED
40xFaster
Swift 1
github.com/knguyen2708/StructVsClassPerformance
37 000 000xFaster
Swift 2 - Whole Module Optimization
github.com/knguyen2708/StructVsClassPerformance
14 000 000xFaster
Swift 3 - Whole Module Optimization
github.com/knguyen2708/StructVsClassPerformance
Use final keyword
unsplash.com/collections/328902/cow
COW (Copy-On-Write)
let a = [1, 2, 3]
var b = a // not copied
b.append(4) // now it’s copied
When I should use a struct ?● The data will be used in code across multiple
threads
When I should use a struct ?● The data will be used in code across multiple
threads● Copies should have independent state
When I should use a struct ?● The data will be used in code across multiple
threads● Copies should have independent state● Encapsulates a few relatively simply data
values
When I should use a class ?● You want to create shared, mutable state
When I should use a class ?● You want to create shared, mutable state● You want to create complex frameworks like
Cocoa or Cocoa Touch
Still undecided ?
Design with struct as default,
fallback to class if it’s really needed.
THANKS !