J. Doe
J. Doe

Reputation: 13043

Create keypath based on parameter

I got this code:

class Person {
    let age = 0
}

func createKeyPath() {
    let ageKeyPath = \Person.age // Works
}

func createKeyPath(from: ???) { // What can I place here to make it compile?
    let ageKeyPath = \from.age
}

I got generic classes and I need to create keypaths on a generic concrete type (like Person), but I am not sure how I can create keypaths based on a parameter. I tried:

func createKeyPath(from: Person.Type) {
    let ageKeyPath = \from.age
}

But it doesn't compile.

Upvotes: 0

Views: 497

Answers (2)

Josh Homann
Josh Homann

Reputation: 16327

Here is a playground example (basically you are going to need to constrain the generic so that the compiler can be sure the KeyPath you are looking for actually exists on that generic type):

import UIKit
import PlaygroundSupport

protocol Ageable {
    var age: Int {get}
}

class Person: Ageable {
    let age = 0
}

func createKeyPath<SomeAgeable: Ageable>(from: SomeAgeable) -> KeyPath<SomeAgeable, Int> {
    return  \SomeAgeable.age
}

let p = Person()
let keyPath = createKeyPath(from: p)
print(p[keyPath: keyPath])

Upvotes: 1

Caleb
Caleb

Reputation: 125007

I need to create keypaths on a generic concrete type (like Person), but I am not sure how I can create keypaths based on a parameter.

A string is used for the keypath parameter in methods that handle keypaths, like value(forKeyPath:).

Upvotes: 0

Related Questions