Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift keyPath vs protocol

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?

like image 967
Tung Vo Duc Avatar asked Sep 22 '26 20:09

Tung Vo Duc


1 Answers

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.

like image 89
matt Avatar answered Sep 25 '26 08:09

matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!