2017-09-25 2 views
0

Ich habe ein Array besteht aus Dictionary.GroupBy Erweiterung Verwendung auf Array auf Swift

Ich muss sie per Schlüssel in einem Wörterbuch gruppieren.

Ich habe versucht, die Linie, aber nicht wissen, was in Handler schreiben. Ich versuche

globalArray.groupBy (Handler: {$ 0 [ "Name"]})

es Fehler ergibt;

Kann Wert des Typs "String?" Nicht konvertieren zu Schließung Ergebnis Typ "_"

meine Gruppe durch Erweiterung ist wie folgt;

extension Sequence { 
// Using a `typealias` because it's shorter to write `E` 
// Think of it as a shortcut 
typealias E = Iterator.Element 

// Declaring a `K` generic that we'll use as the type of the key 
// for the resulting dictionary. The only restriction is having 
// it conforming to the `Hashable` protocol 
func groupBy<K: Hashable>(handler: (E) -> K) -> [K: [E]] { 
    // Creating the resulting dictionary 
    var grouped = [K: [E]]() 

    // Iterating over our elements 
    self.forEach { item in 
     // Retrieving the key based on the current item 
     let key = handler(item) 

     if grouped[key] == nil { 
      grouped[key] = [] 
     } 
     grouped[key]?.append(item) 
    } 

    return grouped 
} 

}

Könnten Sie mir bitte die richtige Nutzung zeigen?

BR,

Erdem

Antwort

1

Ich bin mit diesem extension gruppieren Array, und es funktioniert hervorragend

extension Array { 
    func grouped<T>(by criteria: (Element) -> T) -> [T: [Element]] { 
     var groups = [T: [Element]]() 
     for element in self { 
      let key = criteria(element) 
      if groups.keys.contains(key) == false { 
       groups[key] = [Element]() 
      } 
      groups[key]?.append(element) 
     } 
     return groups 
    } 
} 

Wie verwende ich

array.grouped { (object:MyObjectClass) -> String in 
     return object.location?.name ?? "EmptyKey" 
     //Here you need to return your key 
    } 

Hoffe, es ist hilfreich zu Ihnen