Introduction to Swift Keypaths


released Fri, 29 Mar 2019
Swift Version 5.0

WritableKeyPath<Root, Value>

In the earlier example, our type was a WritableKeyPath. WritableKeyPaths are, as the name implies, keypaths that allow you to write information. They're formed for var properties on var instances.

struct MutableUser {
  var username: String
var firstUser = MutableUser(username: "Shinji")

firstUser[keyPath: \MutableUser.username] = "Ikari"

If you want to have a keypath argument to a function that allows mutating the contents, WritableKeyPath is a good choice:

func modify(user: User, keyPath: WritableKeyPath<User, String>) {
  user[keyPath: keyPath] = "Hello World"

There's another variant of the WritableKeyPath, which we will introduce next.