expressão do caminho principal como funções iOS Swift
struct Car {
var name: String
var kind: String
}
let keyPath = \Car.name // Create key path
var audi = Car(name: "Audi", kind: "luxury") // Create instance of class or struct
print(audi[keyPath: keyPath]) // Access the value of instance
audi[keyPath: keyPath] = "Audi A8 L" // Update the value of instance
print(audi[keyPath: keyPath])
print(audi[keyPath: \.kind]) // Short hand version of key path
let cars = [
audi,
Car(name: "Škoda", kind: "comfort")
]
let carNameList = cars.map(\.name) // in Swift 5.2 we can pass key path as function
print(carNameList)
/* Output will be
Audi
Audi A8 L
luxury
["Audi A8 L", "Škoda"]
*/
Developer101