Imagine I have a struct AStruct:
struct AStruct {
let name: String
let value: Int
}
And imagine I have an array of AStruct
s:
let array: [AStruct] = [
AStruct(name: "John", value: 1),
AStruct(name: "Bob", value: 23),
AStruct(name: "Carol", value: 17),
AStruct(name: "Ted", value: 9),
AStruct(name: "Alice", value: 13),
AStruct(name: "Digby", value: 4)
]
Now imagine I want to use a map()
to create an array of integers out of my array of AStruct
s.
This code works:
let values = array.map { $0.value }
But if I try to use Swift key path syntax I get errors no matter what I try. Example:
let values = array.map { \.value }
I get an error:
Cannot infer key path type from context; consider explicitly specifying a root type.
So how do I that?
I can get it to work if I give the input a name and type:
let values = array.map { (aVal: AStruct) -> Int in
return aVal.value
}
But that is distinctly not key path syntax.