Let’s say I have array of objects that can be identified and I want to create dictionary from it. I can easily get tuples from my array like so:
let tuples = myArray.map { return ($0.id, $0) }
But I can’t see initializer for dictionary to take array of tuples. Am I missing something? Do I have create extension for dictionary for this functionality (in fact it’s not hard but I thought it would be supplied by default) or there is easier way to do that?
There is code for extension
extension Dictionary { public init (_ arrayOfTuples : Array<(Key, Value)>) { self.init(minimumCapacity: arrayOfTuples.count) for tuple in arrayOfTuples { self[tuple.0] = tuple.1 } } }
Using the append function we just added the values to the dictionary. This is a simple method of conversion from a list or tuple to a dictionary. Here we pass a tuple into the dict() method which converts the tuple into the corresponding dictionary.
When it is required to add a dictionary to a tuple, the 'list' method, the 'append', and the 'tuple' method can be used. A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on). The 'append' method adds elements to the end of the list.
Only immutable elements can be used as dictionary keys, and hence only tuples and not lists can be used as keys.
Swift 4
If your tuples is (Hashable, String) you can use:
let array = [("key1", "value1"), ("key2", "value2"), ("key3", "value3")] let dictionary = array.reduce(into: [:]) { $0[$1.0] = $1.1 } print(dictionary) // ["key1": "value1", "key2": "value2", "key3": "value3"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With