How to transform array to dictionary in Swift
In Swift, you can use the map
method to transform an array into a new array of the same size, where a provided closure has changed each element. To convert an array to a dictionary, you can use the reduce
method. Here's an example of how to map an array of integers to a dictionary where the key is the integer, and the value is its double:
let integers = [1, 2, 3, 4, 5]
let doubled = integers.reduce(into: [:]) { $0[$1] = $1 * 2 }
print(doubled) // [1: 2, 2: 4, 3: 6, 4: 8, 5: 10]
Or you can use the Dictionary
init method like this:
let array = [1, 2, 3, 4, 5]
let dictionary = Dictionary(uniqueKeysWithValues: array.map { ($0, $0 * 2) })
print(dictionary) // [1: 2, 2: 4, 3: 6, 4: 8, 5: 10]
You can also use zip
method to map array to dictionary
let array = [1, 2, 3, 4, 5]
let keys = array
let values = array.map { $0 * 2 }
let dictionary = Dictionary(uniqueKeysWithValues: zip(keys, values))