convert dictionary values to array 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)