Peter71 Peter71 - 2 months ago 15
Swift Question

Swift 3: array to Dictionary?

I have a large array und need to access it by a key (a lookup). So I need to create Dictionary. Is there a build in functionlity in Swift 3.0 to do so, or do I need to write it by my own?
First I will need it for a class with key "String", later on maybe I will be able to write a template version for general purpose (all types of data and key).

Answer

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.

Comments