假设您想要跟踪一个或多个唯一标识符。在这种情况下,A
有两个属性被认为是唯一的A
,而B
只有一个属性是唯一的B
。
protocol HavingUID {
// Some way to use KeyPath?
}
struct A : HavingUID {
var unique1 : String
var unique2 : Int
}
struct B : HavingUID {
var unique1 : Double
}
let a1 = A(unique1:"val", unique2: 1)
let a2 = A(unique1:"val", unique2: 2)
let b1 = B(unique1:0.5)
let b2 = B(unique1:0.0)
let b3 = B(unique1:0.2)
let arrA : [HavingUID] = [a1,a2]
let arrB : [HavingUID] = [b1,b2,b3]
// How to check arrA and arrB for duplicate UID properties?
如果只有一个唯一键,我们可以这样做:
protocol HavingUID {
typealias UID
static var uidKey : KeyPath<Self, UID> {get}
}
struct A : HavingUID {
static var uidKey = A.\unique1
var unique1 : String
}
struct B : HavingUID {
static var uidKey = B.\uniqueB
var uniqueB : Int
}
...但这将我限制在一把钥匙上。