(The question is motivated by How to Convert array to Dictionary (without Loop) on Stack Overflow.)
I wonder why the following code does not compile:
let array = ["zero", "one", "two", "three"]
let dict = Dictionary(uniqueKeysWithValues: array.enumerated())
// Generic parameter 'Key' could not be inferred
Specifying key and value type does not help:
let array = ["zero", "one", "two", "three"]
let dict = Dictionary<Int, String>(uniqueKeysWithValues: array.enumerated())
// Generic parameter 'S' could not be inferred
As far as I can tell, enumerated()
here returns a sequence of (offset: Int, element: String)
pairs, so I would have expected that the above can be used to create a [Int: String]
dictionary. Is that because the tuples are labeled?
Creating an intermediate array makes it compile and work:
let array = ["zero", "one", "two", "three"]
let dict = Dictionary<Int, String>(uniqueKeysWithValues: Array(array.enumerated()))
print(dict) // [2: "two", 0: "zero", 1: "one", 3: "three"]
I am also aware that there are alternative solutions, such as
let dict = Dictionary(uniqueKeysWithValues: zip(array.indices, array))
but I am curious why the first approach does not work.
Regards, Martin