Swift equivalent to `[NSDictionary initWithObjects: forKeys:]`

后端 未结 5 1376
别跟我提以往
别跟我提以往 2020-11-27 07:41

Is there an equivalent for Swift\'s native Dictionary to [NSDictionary initWithObjects: forKeys:]?

Say I have two arrays with keys and valu

5条回答
  •  温柔的废话
    2020-11-27 08:21

    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"
    

提交回复
热议问题