0

我得到了这个代码:

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
}

我有通用类,我需要在通用具体类型(如 Person)上创建键路径,但我不确定如何基于参数创建键路径。我试过了:

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

但它不编译。

4

2 回答 2

1

这是一个游乐场示例(基本上您将需要约束泛型,以便编译器可以确定您正在寻找的 KeyPath 确实存在于该泛型类型上):

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])
于 2019-04-10T18:49:26.930 回答
0

我需要在通用具体类型(如 Person)上创建键路径,但我不确定如何基于参数创建键路径。

字符串用于处理键路径的方法中的键路径参数,例如value(forKeyPath:).

于 2019-04-10T18:23:43.577 回答