Ho implementato un set in Swift che utilizza le chiavi del dizionario. Voglio implementare un metodo addAll (sequenza) che prende qualsiasi tipo di sequenza sugli Elementi nel Set, ma sto ricevendo un errore che non ha senso. Ecco il mio codiceImplementazione Set.addSequence in Swift
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
}
}
sto ottenendo questo errore in XCode 6.1 e 6.0.1.
Volevo seguire la semantica del metodo di estensione di Array, ma quella firma di tipo non viene nemmeno compilata per me.
Sto facendo qualcosa di sbagliato, o dovrei presentare un radar?
modifica: appena trovato https://github.com/robrix/Set/blob/master/Set/Set.swift, che ha questa implementazione:
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)
}
}
Tuttavia, che appena converte sequence
in un Array
, che tipo di sconfigge lo scopo di SequenceType
tutto.
Sono d'accordo che questo è un bug. Qualcuno lo ha segnalato? Grazie – drasto
@drasto: non lo so. Ma in ogni caso, se sei affetto da questo problema, invia il tuo bug report. –
L'uso di 'map' sembra la soluzione migliore. Suppongo che il problema principale sia che 'map' non dovrebbe permettere effetti collaterali. – bart