【问题标题】:In Swift, what is the best way to assign two arrays to key/value of a dictionary?在 Swift 中,将两个数组分配给字典的键/值的最佳方法是什么?
【发布时间】:2014-06-06 08:30:25
【问题描述】:

假设我有两个数组:

let myKeys = ["one", "two", "three"]
let myValues = ["1",  "2", "3"]

和空字典:

var myDictionary = Dictionary<String, String>()

myKeysmyValues 分别分配为myDictionary 的键和值的最佳方法是什么?

【问题讨论】:

    标签: dictionary swift


    【解决方案1】:

    据我所知,这是为您的字典分配值/键的方法:

    let count = myKeys.count
    let count2 = myValues.count
    if (count == count2) {
        for index in 0..count {
            myDictionary.updateValue(myValues[index], forKey:myKeys[index])
        }
    }
    

    编辑:Swift 2

    let count = myKeys.count
    let count2 = myValues.count
    if (count == count2) {
        for index in 0 ..< count {
            myDictionary.updateValue(myValues[index], forKey:myKeys[index])
        }
    }
    

    【讨论】:

    • 你确定不要0..count
    • 但现在它只从 0 变为 count-2。
    猜你喜欢
    • 2019-04-21
    • 1970-01-01
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    • 2011-03-20
    • 1970-01-01
    • 2010-11-11
    相关资源
    最近更新 更多