Search code examples
arraysdictionaryfilterswift3

Swift 3: Array to Dictionary?


I have a large array and need to access it by a key (a lookup) so I need to create Dictionary. Is there a built in function in Swift 3.0 to do so, or do I need to write it myself?

First I will need it for a class with key "String" and later on maybe I will be able to write a template version for general purpose (all types of data and key).


Solution

  • I think you're looking for something like this:

    extension Array {
        public func toDictionary<Key: Hashable>(with selectKey: (Element) -> Key) -> [Key:Element] {
            var dict = [Key:Element]()
            for element in self {
                dict[selectKey(element)] = element
            }
            return dict
        }
    }
    

    You can now do:

    struct Person {
        var name: String
        var surname: String
        var identifier: String
    }
    
    let arr = [Person(name: "John", surname: "Doe", identifier: "JOD"),
               Person(name: "Jane", surname: "Doe", identifier: "JAD")]
    let dict = arr.toDictionary { $0.identifier }
    
    print(dict) // Result: ["JAD": Person(name: "Jane", surname: "Doe", identifier: "JAD"), "JOD": Person(name: "John", surname: "Doe", identifier: "JOD")]
    

    If you'd like your code to be more general, you could even add this extension on Sequence instead of Array:

    extension Sequence {
        public func toDictionary<Key: Hashable>(with selectKey: (Iterator.Element) -> Key) -> [Key:Iterator.Element] {
            var dict: [Key:Iterator.Element] = [:]
            for element in self {
                dict[selectKey(element)] = element
            }
            return dict
        }
    }
    

    Do note, that this causes the Sequence to be iterated over and could have side effects in some cases.