Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR SWIFT

key path expression as functions 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"]
*/
Source by gist.github.com #
 
PREVIOUS NEXT
Tagged: #key #path #expression #functions #ios #swift
ADD COMMENT
Topic
Name
9+1 =