Swift Key Paths

Hello. I was wondering if someone could point me to an example of a good use case for Swift’s key path syntax. I see them more often now in SwiftUI and Combine, but typically, you also need to provide an object with the key path. Why use a key path if you have an object and could simply use dot syntax to read/write to the property?

John Sundell explains it well in his article:
“Key paths essentially let us reference any instance property as a separate value. As such, they can be passed around, used in expressions, and enable a piece of code to get or set a property without actually knowing which exact property its working with.”

Also have a look at pointfree.co’s playgrounds on functional getters and setters. PointFree has many episodes that show key path usage extensively as well as many other interesting topics.

This topic was automatically closed after 166 days. New replies are no longer allowed.