声明一个Swift协议,它具有属性返回值CollectionType <Int>?

Noo*_*bie 9 protocols swift

是这样的

protocol A {
    var intCollection: CollectionType<Int> { get }
}
Run Code Online (Sandbox Code Playgroud)

要么

protocol A {
    typealias T: CollectionType where T.Generator.Element == Int
    var intCollection: T
}
Run Code Online (Sandbox Code Playgroud)

可以在Swift 2.1中使用吗?


Swift 4的更新

Swift 4现在支持此功能!在这里阅读更多内容

Rob*_*ier 0

不是作为嵌套协议,但使用类型擦除器(“Any”结构)相当简单。

protocol A {
    var intCollection: AnyRandomAccessCollection<Int> { get }
}
Run Code Online (Sandbox Code Playgroud)

这实际上对于返回值来说通常非常方便,因为调用者通常不太关心实际类型。你只需要return AnyRandomAccessCollection(resultArray)在函数末尾添加 a 就可以了。许多 stdlib 现在返回Any橡皮擦。对于返回值问题,几乎都是我推荐的方式。它具有制造混凝土的良好副作用A,因此更容易使用。

如果您想保留CollectionType,那么您需要在创建需要它的函数时对其进行限制。例如:

protocol A {
    typealias IntCollection: CollectionType
    var intCollection: IntCollection { get }
}

extension A where IntCollection.Generator.Element == Int {
    func sum() -> Int {
        return intCollection.reduce(0, combine: +)
    }
}
Run Code Online (Sandbox Code Playgroud)

这并不理想,因为这意味着您可能会使用A错误的集合类型。他们只是没有sum办法。您还会发现自己在数量惊人的地方重复“where IntCollection.Generator.Element == Int”。

根据我的经验,这种努力很少值得,并且您很快就会回到数组(无论如何,数组都是占主导地位的 CollectionType)。但当你需要它时,这是两种主要方法。这就是我们今天所拥有的最好的。