除了冗余的介绍,我希望有这样的东西:
let collection : Any<Sequence where .Iterator.Element == String> = ...
Run Code Online (Sandbox Code Playgroud)
要么
let collection : Sequence<where .Iterator.Element == String> = ...
Run Code Online (Sandbox Code Playgroud)
这被称为Apple的Generics Manifesto中的 "Generalized Existentials" .(我认为)我真的需要这个用于许多用例和这个:
协议'P'只能用作通用约束,因为它具有Self或相关类型要求.
使"第一个面向协议的语言"对我来说很难理解.缺乏这一点使我打击Swift的类型系统并创建不利的通用"抽象"类,其中应该有一个协议associatedtype.
这是一个让我受命最多的例子,代表一个泛型类:
protocol GenericClassDelegate : class {
associatedtype ItemType
func didDoThat(who : GenericClass<ItemType>)
}
class GenericClass<T> {
weak var delegate : GenericClassDelegate<where .ItemType == T>? // can't do that
func notify() {
delegate?.didDoThat(who: self)
}
}
Run Code Online (Sandbox Code Playgroud)
虽然我可以描述GenericClassDelegate协议,但我(目前在Swift 3中)不能具有该类型的变量或常量(或任何符合限制的类型).
不要混淆这个问题与如何将泛型协议用作泛型类的变量类型或Swift委托协议,因为我的问题是: