我得到了这样的代码:
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)上创建keypath,但我不确定如何才能基于参数创建keypath。我试过了:
func createKeyPath(from: Person.Type) {
let ageKeyPath = \from.age
}但是它不能编译。
发布于 2019-04-11 02:49:27
这是一个游乐场的例子(基本上你需要约束泛型,以便编译器可以确保你正在寻找的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-11 02:23:44
我需要在泛型的具体类型(如Person)上创建keypath,但我不确定如何基于参数创建keypath。
字符串用于处理密钥路径的方法中的密钥路径参数,如value(forKeyPath:)。
https://stackoverflow.com/questions/55618933
复制相似问题