Is there an equivalent for Swift\'s native Dictionary
to [NSDictionary initWithObjects: forKeys:]
?
Say I have two arrays with keys and valu
Working pure Swift solution with structs. Use zip
to iterate through your two arrays as a tuple, and then create a dictionary for each key, value in the tuple.
struct SomeStruct {
var someVal: Int?
}
var keys = [String]()
var values = [SomeStruct]()
for index in 0...5 {
keys.append(String(index))
values.append(SomeStruct(someVal: index))
}
var dict = [String : Any]()
for (key, value) in zip(keys, values) {
dict[key] = value
}
print(dict) // "["4": SomeStruct(someVal: Optional(4)), "2": SomeStruct(someVal: Optional(2)), "1": SomeStruct(someVal: Optional(1)), "5": SomeStruct(someVal: Optional(5)), "0": SomeStruct(someVal: Optional(0)), "3": SomeStruct(someVal: Optional(3))]"
You could also use forEach
on zip
:
var dict = [String : Any]()
zip(keys, values).forEach { dict[$0.0] = $0.1 }
print(dict) // "["4": SomeStruct(someVal: Optional(4)), "2": SomeStruct(someVal: Optional(2)), "1": SomeStruct(someVal: Optional(1)), "5": SomeStruct(someVal: Optional(5)), "0": SomeStruct(someVal: Optional(0)), "3": SomeStruct(someVal: Optional(3))]\n"