I understand the basic idea of keyPaths but I do not understand its use cases. If you already know the type of the instance, you can access their properties easily. If you don’t, protocol already supports read-only, read-write properties. Can someone explain me what I am missing? Anything that we can’t do with protocols but keyPaths or when keypaths are better than protocols?
If you already know the type of the instance, you can access their properties easily. If you don’t, protocol already supports read-only, read-write properties. Can someone explain me what I am missing?
What you're missing is a sense of what's unknown.
In both your sentences you speak of knowing what the instance's properties are. That's not the problem key paths solve. Key paths have nothing to do with knowing the type; they are not in any kind of opposition to types or protocols. On the contrary, before you can use a key path, you have to know exactly what the instance's properties are.
Key paths are for when what is unknown is which property to access. They provide a way to pass a property reference so that someone else can be told to access that property.
For example, here's a Person type:
struct Person {
let firstName : String
let lastName : String
}
And here is a function that sorts an array of Persons by either the firstName
or the lastName
, without knowing which one to sort by:
func sortArrayOfPersons(_ arr:[Person], by prop: KeyPath<Person, String>) -> [Person] {
return arr.sorted { $0[keyPath:prop] < $1[keyPath:prop] }
}
A key path is how you tell this function what property to use as a basis for sorting.