我有一个协议协议SCResourceModel {..}和一个字典,它将使用这个协议类型作为密钥:[SCResourceModel:String].
这显然不起作用,因为字典中的键必须符合Hashable协议.使我的SCResourceModel继承自Hashable或尝试类似这样的东西[protocol< SCResourceModel,Hashable> :String]显然不起作用,因为Hashable或Equatable只能用作泛型约束而不能用作类型本身.
我观看了WWDC 2015和Swift 2.0,可以为协议添加约束,例如:protocol SCResourceModel,其中Self:Hashable {..}直接解决了这个问题(非常好).
无论如何,我的问题是:我可以使用当前的Swift 1.2版本做类似的事情,并以某种方式使用此协议作为字典的关键字吗?或者任何人都可以提出一个很好的解决方法或其他我可能忽略的东西?
我目前在Swift 1.2中看到的唯一解决方案是将协议转换为继承自例如Swift 1.2的类. NSObject并且必须在我的API中进一步使用子类.
谢谢你的帮助!
解决方法 我可能会想到:protocol SCResourceModel { var hashValue: Int { get } func isEqualTo(another: SCResourceModel) -> Bool // ...}struct SCResourceModelWrapper: Equatable,Hashable { let model: SCResourceModel var hashValue: Int { return model.hashValue ^ "\(model.dynamicType)".hashValue }}func == (lhs: SCResourceModelWrapper,rhs: SCResourceModelWrapper) -> Bool { return lhs.model.isEqualTo(rhs.model)}struct SCResourceModelDictionary<T> { private var storage = [SCResourceModelWrapper: T]() subscript(key: SCResourceModel) -> T? { get { return storage[SCResourceModelWrapper(model: key)] } set { storage[SCResourceModelWrapper(model: key)] = newValue } }}总结
以上是内存溢出为你收集整理的ios – 以协议类型为键的Swift字典全部内容,希望文章能够帮你解决ios – 以协议类型为键的Swift字典所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)