array to dictionary swift code example
Example 1: swift convert array to dictionary
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
}
}
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)
Example 2: convert dictionary to array swift
let dic = ["1":"a", "2":"b", "3":"c"]
let arrayOfKeys = Array(dic.keys.map{ $0 })
print(arrayOfKeys)
let arrayOfValues = Array(dic.values.map{ $0 })
print(arrayOfValues)
Example 3: swift map array to dictionary
let myDictionary = myArray.reduce([Int: String]()) { (dict, person) -> [Int: String] in
var dict = dict
dict[person.position] = person.name
return dict
}