首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用协议定义具有不同值的KeyPaths集合

使用协议定义具有不同值的KeyPaths集合
EN

Stack Overflow用户
提问于 2020-09-04 10:21:00
回答 1查看 33关注 0票数 0

假设您想要跟踪一个或多个唯一标识符。在本例中,A有两个被认为是A独有的属性,而B只有一个属性是B独有的。

代码语言:javascript
复制
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?

如果只有一个唯一的键,我们可以这样做:

代码语言:javascript
复制
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
}

...but,这将我限制为一个密钥。

EN

回答 1

Stack Overflow用户

发布于 2020-09-04 12:34:26

无论何时需要使用唯一标识符,都应该使用全局结构或枚举来跟踪它们。这里有两种简单的方法可以做到这一点:

结构:

代码语言:javascript
复制
struct UniqueIdentifiers {
    static let id1 = "identifier_one"
    static let id2 = "identifier_two"
    static let id3 = "identifier_three"
}

let currentID = UniqueIdentifiers.id1

枚举:

代码语言:javascript
复制
enum UniqueIdentifiers: String {
    case id1 = "identifier_one"
    case id2 = "identifier_two"
    case id3 = "identifier_three"
}

let currentID = UniqueIdentifiers.id1.rawValue
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63733958

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档