I implemented a set in Swift that uses dictionary keys. I want to implement the addAll (sequence) method, which accepts any type of sequence over elements in Set, but I get an error that does not make sense. Here is 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 type 'S' to type 'S' hash[element] = true } } mutating func remove(element: Element) { hash[element] = nil } }
I get this error in Xcode 6.1 and 6.0.1.
I wanted to follow the semantics of the Array extension method, but a signature of this type does not even compile for me.
Am I doing something wrong, or do I need to file a radar?
edit : just found https://github.com/robrix/Set/blob/master/Set/Set.swift that 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, this simply converts the sequence to Array , which generally hits the target of the SequenceType .
source share