Normally a property is initialized in one line
let oneLineInitializedProperty : Int = 5
But for properties that require more than a one-liner to be initialized, there is a special syntax: = {}()
When the property is first accessed, the closure is executed (only once, note the parentheses at the end), and its return value is stored in the property.
let multilineInitilizedProperty: Int = {
//custom code calculating the value
//return the value
}()
var
orlet
struct
andclass
(not enum nor extension)
class TeslaCar {
var modelName: String?
}
struct TeslaCar {
let modelName: String
var price: Int
}
- only
var
struct
,class
,enum
andextension
closure
syntax
class TeslaCarModel3 {
var modelName: String {
return "Model 3"
}
}
struct TeslaCarModelS {
var modelName: String {
return "Model S"
}
}
enum TeslaCarModelX {
var modelName: String {
return "Model X"
}
}
extension TeslaCarModelS {
var price : Int {
return 70_000
}
}
- only
var
struct
andclass
(not enum nor extension)- prefix
lazy
class TeslaCarModel3 {
lazy var modelName: String = "Model 3"
}
struct TeslaCarModelS {
lazy var modelName: String = "Model S"
}
class TeslaCar {
private let modelName: String!
//This is a lazy loaded property which requires more than one line to initialize and references self
lazy var priceForCustomers: Int = {
switch (self.modelName) { //In lazily loaded varaibles, self must be used explicitly!
case "Model 3": return 30_000
case "Model S": return 70_000
default: return 100_000
}
}()
init(modelName: String) {
self.modelName = modelName
}
}