I've implemented a Set in Swift that uses Dictionary keys. I want to implement an addAll(sequence) method that takes any sequence type over the Elements in the Set, but I'm getting an error that doesn't make sense. Here's my code
struct Set<Element: Hashable> {
var hash = [Element: Bool]()
init(elements: [Element] = []) {
for element in elements {
self.hash[element] = true
}
}
var array: [Element] {
return hash.keys.array
}
func contains(element: Element) -> Bool {
return hash[element] ?? false
}
mutating func add(element: Element) {
hash[element] = true
}
mutating func add(array: [Element]) {
for element in array {
hash[element] = true
}
}
mutating func add<S : SequenceType where S.Generator.Element == Element>(sequence: S) {
for element in sequence { // Error here: "Cannot convert the expression's type 'S' to type 'S'
hash[element] = true
}
}
mutating func remove(element: Element) {
hash[element] = nil
}
}
I'm getting this error in XCode 6.1 and 6.0.1.
I wanted to follow the semantics of Array's extend method, but that type signature doesn't even compile for me.
Am I doing something wrong, or should I file a Radar?
edit:
just found https://github.com/robrix/Set/blob/master/Set/Set.swift, which has this implementation:
public mutating func extend<S : SequenceType where S.Generator.Element == Element>(sequence: S) {
// Note that this should just be for each in sequence; this is working around a compiler crasher.
for each in [Element](sequence) {
insert(each)
}
}
However, that just converts sequence
into an Array
, which kind of defeats the purpose of SequenceType
altogether.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…