let keys = ["one", "two", "three"] let values = [1, 2, 3] func createDict<K:Hashable,V>(keys: [K], values:[V])->[K:V] { var dict: [K:V] = [:] // add validity checks here by yourself ! // and return early, or throw an error ... keys.enumerate().forEach { (index,element) -> () in dict[element] = values[index] } return dict } let dict = createDict(keys, values: values) // ["one": 1, "three": 3, "two": 2] let dict2:[Int:Any] = createDict([1,2,3,4,5], values: [true,"two",3.4,5,[1,2,3]]) // [5: [1, 2, 3], 2: "two", 3: 3.4, 1: true, 4: 5]
What is the difference when comparing it with a zip solution? hard to say ... for me, zip annotation is the biggest problem
let a:Zip2Sequence<[Int],[Any]> = zip([1,2,3,4,5], [true,"two",3.4,5,[1,2,3]]) var d:[Int:Any] = [:] a.forEach { (key, value) -> () in d[key] = value } print(d)
but listing the solution is also a little faster