DEV Community

David Goyes
David Goyes

Posted on

Swift #15: Key Paths

Un "key path" es una referencia a una propiedad de una instancia que puede ser pasada como argumento a una función, para acceder a los valores de una instancia.

Los "key path"s de solo lectura están almacenados en una estructura de tipo KeyPath, mientras que los de lectura-y-escritura están en WritableKeyPath.

La sintaxis de un "key path" es: \TipoDeDato.nombreDePropiedad.

Para acceder a un valor por medio de un "Key path" se usa la notación: instancia[keyPath].

Por ejemplo:

struct Person {
  let name = "David"
  var age = 10
}

var instance1 = Person()

let ageKeyPath = \Person.age
// ageKeyPath: any WritableKeyPath<Person, Int>
instance1[keyPath: ageKeyPath] = 11

let nameKeyPath = \Person.name
// nameKeyPath: any KeyPath<Person, String>

print("Persona: \(instance1[keyPath: nameKeyPath]) \(instance1.age)") // Persona: David 11
Enter fullscreen mode Exit fullscreen mode

Top comments (0)