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

后端 未结 5 1412
别跟我提以往
别跟我提以往 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:13

    A one-liner, using zip and reduce:

    let dict = zip(keys, values).reduce([String:Int]()){ var d = $0; d[$1.0] = $1.1; return d }
    

    You can shorten the reduce expression by defining the + operator for a Dictionary and a tuple:

    func +(lhs: [K:V], rhs: (K, V)) -> [K:V] {
        var result = lhs
        result[rhs.0] = rhs.1
        return result
    }
    
    let dict = zip(keys, values).reduce([String:Int](), combine: +)
    

提交回复
热议问题