Cal*_*ter 7 casting swift swift4 keypaths
我有一个枚举案例数组,其中每个案例都有一个keyPath属性,该属性返回AnyKeyPath与枚举案例同名的匹配类属性:
protocol PathAccessor: CodingKey {
var keyPath: AnyKeyPath { get }
static var allCases: [Self] { get }
init?(rawValue: Int)
}
extension PathAccessor {
static var allCases: [Self] {
var cases: [Self] = []
var index: Int = 0
while let element = Self.init(rawValue: index) {
cases.append(element)
index += 1
}
return cases
}
}
class Robot {
let name: String
var age: Int
var powered: Bool
var hasItch: Bool?
enum CodingKeys: Int, PathAccessor {
case name
case age
case powered
case hasItch
var keyPath: AnyKeyPath {
switch self {
case .name: return \Robot.name
case .age: return \Robot.age
case .powered: return \Robot.powered
case .hasItch: return \Robot.hasItch
}
}
}
init(name: String, age: Int, powered: Bool) {
self.name = name
self.age = age
self.powered = powered
}
}
for element in Robot.CodingKeys.allCases {
// Trying to implement
}
Run Code Online (Sandbox Code Playgroud)
在上面的循环中,我想检查keyPathcase 的属性以查看它是否是 a WritableKeyPath,如果是,则创建一个闭包来修改键路径访问的属性。
问题在于 aWritableKeyPath是泛型类型。我知道该Root类型,但该Value类型几乎可以是现有的任何类型。我可以为每种最可能的类型创建一堆案例:
if let path = element.keyPath as? WritableKeyPath<Robot, Int> {
} else if let path = element.keyPath as? WritableKeyPath<Robot, String> {
} // So on and so forth
Run Code Online (Sandbox Code Playgroud)
但这非常耗时、丑陋且难以维护。
我确实尝试转换为动态类型,但这会产生编译器错误(Use of undeclared type 'valueType'):
let valueType = type(of: element.keyPath).valueType
guard let path = element.keyPath as? WritableKeyPath<Self, valueType> else {
continue
}
Run Code Online (Sandbox Code Playgroud)
我可以使用类型已经符合的协议,但由于某种原因,这也失败了:
guard let path = element.keyPath as? WritableKeyPath<Robot, NodeInitializable> else {
print("bad")
continue
}
print("good")
// Output:
// bad
// bad
// bad
// bad
Run Code Online (Sandbox Code Playgroud)
那么,是否有可能将 an 转换AnyKeyPath为 a WritableKeyPath,而不需要大量的展开语句或不应该在生产中使用的奇怪的 hack?
经过几个小时的代码研究,我得到的最好的结果是:
struct Person {
var name: String
var collection: [String]
var optionalCollection: [String]?
let birthdate: Date
fileprivate func keyPath<V>(from label: String, type: V.Type) -> WritableKeyPath<Person, V> {
print("type: \(type)")
let valuePair: [String: PartialKeyPath<Person>] = ["name": \Person.name,
"birthdate": \Person.birthdate,
"collection": \Person.collection,
"optionalCollection": \Person.optionalCollection]
return valuePair[label] as! WritableKeyPath<Person, V>
}
}
var person = Person(name: "john",
collection: [],
optionalCollection: ["gotcha"],
birthdate: Date(timeIntervalSince1970: 0))
let name = person[keyPath: person.keyPath(from: "name", type: String.self)] // john
let birthdate = person[keyPath: person.keyPath(from: "birthdate", type: Date.self)] // Jan 1, 1970
let collection = person[keyPath: person.keyPath(from: "collection", type: Array<String>.self)] // []
let optionalCollection = person[keyPath: person.keyPath(from: "optionalCollection", type: Optional<Array<String>>.self)] // ["gotcha"]
Run Code Online (Sandbox Code Playgroud)
但是,您必须始终将类型作为参数传递。如果只有 Mirror 类允许我们从每个属性获取实际类型就好了。
| 归档时间: |
|
| 查看次数: |
5330 次 |
| 最近记录: |