Swift中的设置和协议 [英] Set and protocols in Swift

查看:164
本文介绍了Swift中的设置和协议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用与Hashable协议和自定义协议相对应的值初始化Set。

I would like to initialize a Set with values corresponding to the Hashable protocol and a custom protocol.

我试过:

protocol CustomProtocol: Hashable {}

let set = Set<CustomProtocol>()

但Xcode抱怨:


使用'CustomProtocol'作为符合协议的具体类型
'Hashable'不受支持

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

我如何实现这一目标?

How can I achieve that ?

提前致谢。

推荐答案

你能做到的直接原因做你想做的是Hashable是一种通用协议。因此,它 - 或从中派生的协议 - 不能用作Set的元素类型。泛型类型只能用作另一个泛型中的约束。您会注意到,即使set的元素类型必须符合为Hashable,您也不能声明 Set< Hashable>

The immediate reason why you can't do what you want to do is that Hashable is a generic protocol. Thus it — or a protocol that derives from it — cannot be used as a Set's element type. A generic type can used only as a constraint in another generic. You will notice that you can't declare a Set<Hashable> either, even though a set's element type must conform to Hashable.

最简单的方法是制作一组协议,而不是一组对象类型。例如,如果S是符合CustomProtocol的结构(因为它符合Hashable加上CustomProtocol所需的任何其他内容),则可以声明一组S。

The simplest approach is to make, not a set of protocols, but a set of some object type. For example, if S is a struct that conforms to CustomProtocol (because it conforms to Hashable plus whatever else CustomProtocol entails), you can declare a set of 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>()

如果你想要解决的问题是你想要一个混合类型的集合,但它们在某种程度上是彼此相同的,那么协议扩展就解决了同样的问题,如下所述面向协议的WWDC 2015视频中的讨论。

If the problem you're trying to solve is that you want a collection of mixed types which are nevertheless in some way equatable to one another, then that is the very same problem solved by protocol extensions, as explained by the discussion in the Protocol-Oriented WWDC 2015 video.

但是,只需要创建源自NSObject的所有类型类,这样做会更简单。当然,你仍然可以让它们采用一些辅助协议,但是这个集合不会被定义为NSObject的一套协议。

But it would be simpler just to make all your types classes that derive from NSObject. You can still make them adopt some secondary protocol, of course, but the set won't be defined as a set of that protocol but of NSObject.

这篇关于Swift中的设置和协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆