[英]Create keypath based on parameter
我得到以下代码:
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
}
但是它不能编译。
这是一个操场示例(基本上,您将需要限制泛型,以便编译器可以确保您要查找的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])
我需要在通用的具体类型(例如Person)上创建键路径,但是我不确定如何基于参数创建键路径。
在处理键路径的方法value(forKeyPath:)
例如value(forKeyPath:)
,字符串用作键路径参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.