ios - Swift 中的集合和协议(protocol)

标签 ios swift

我想用对应于 Hashable 协议(protocol)和自定义协议(protocol)的值来初始化一个 Set。

我试过了:

protocol CustomProtocol: Hashable {}

let set = Set<CustomProtocol>()

但是 Xcode 提示:

Using 'CustomProtocol' as a concrete type conforming to protocol 'Hashable' is not supported

我怎样才能做到这一点?

提前致谢。

最佳答案

你不能做你想做的事情的直接原因是 Hashable 是一个通用协议(protocol)。因此它——或从它派生的协议(protocol)——不能用作 Set 的元素类型。泛型类型只能用作另一个泛型中的约束。你会注意到你不能声明 Set<Hashable>要么,即使集合的元素类型必须符合 Hashable。

最简单的方法不是创建一组协议(protocol),而是创建一组某种对象类型。例如,如果 S 是一个符合 CustomProtocol 的结构(因为它符合 Hashable 以及 CustomProtocol 的任何其他要求),您可以声明一组 S。

例子:

protocol CustomProtocol: Hashable {

}

func ==(lhs:S,rhs:S) -> Bool {
    return lhs.name == rhs.name
}

struct S : CustomProtocol {
    var name : String
    var hashValue : Int { return name.hashValue }
}

let set = Set<S>()

如果您要解决的问题是您想要一组混合类型,但这些类型在某种程度上可以等同于彼此,那么这与协议(protocol)扩展解决的问题完全相同,如中的讨论所述面向协议(protocol)的 WWDC 2015 视频。

但是如果让所有的类型类都派生自 NSObject 会更简单。当然,您仍然可以让它们采用一些辅助协议(protocol),但是该集合不会被定义为该协议(protocol)的集合,而是 NSObject 的集合。

关于ios - Swift 中的集合和协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33189345/

相关文章:

ios - 如何在 Swift iOS 中将字符串转换为日期字符串?

如果使用索引,Swift 可以更改用 let 声明的结构,但如果使用循环则不能

Swift CGPDFContextBeginPage 和 CFData

swift - 播放文档目录中的 m4a 文件

ios - 从其他应用程序和 NotificationCenter 接收有意义的通知

ios - 在不同重复间隔的Apple Watch上添加提醒通知

iphone - "autoreleased with no pool in place - just leaking"仅适用于 iOS 4.3

ios - PFArrayResultBlock(parse) 在转换为 swift 2.0 时导致错误

iphone - 雅虎天气 API 的 XML 解析器问题

swift - 在 Swift 中获取字符串中子字符串位置的可靠函数