我有一个类,它应该提供一个基于集合的随机生成器。
由于它是一个随机生成器(next() 永远不会返回 nil,除非集合为空),我不希望能够将此生成器用作 sequenceType(不支持“for in”以避免无限循环)
我似乎无法正确获取方法签名。
这是我构建的框架,我包含了 3 次尝试及其相应的编译器错误。
public protocol myProtocol {
var name : String { get }
}
internal struct myProtocolStruct: myProtocol {
let name : String
init(name: String) {
self.name = name
}
}
internal struct myGenerator : GeneratorType {
let names : [myProtocol]
init(names: [myProtocol]) {
self.names = names
}
mutating func next() -> myProtocol? {
return names.first
}
}
public class myClass {
private var items : [myProtocol]
public init() {
let names = ["0", "1", "2"]
items = names.map{ myProtocolStruct(name: $0) }
}
public func generate0() -> GeneratorType { // error: protocol 'GeneratorType' can only be used as a generic constraint because it has Self or associated type requirements
let x = myGenerator(names: items)
return x
}
public func generate1<C: GeneratorType where C.Element == myProtocol>() -> C {
let x = myGenerator(names: items)
return x // error: 'myGenerator' is not convertible to 'C'
}
public func generate2<C: GeneratorType where C.Element: myProtocol>() -> C {
let x = myGenerator(names: items)
return x // error: 'myGenerator' is not convertible to 'C'
}
}