使用数组数据将值赋入字典 - swift

时间:2016-02-14 05:28:39

标签: arrays swift dictionary

我真的没有得到这个 - 为什么这不起作用?

var listOfFruit = ["Apple", "Banana","Lemon"]
var emptyDict = [String: String]()
var key = ["Name of Fruit","Name of Fruit","Name of Fruit"]

func createDictionary(){
    var index: Int
    index = listOfFruit.count

    for index in listOfFruit {
        emptyDict = [key[index]:listOfFruit[index]]
        print (emptyDict)
    }
}

我很平常:

1 个答案:

答案 0 :(得分:0)

我正在猜测你需要什么,因为你的问题很不清楚。

给出此输入

IF

var fruits = ["Apple", "Banana","Lemon"]
var keys = ["Name of Fruit", "Name of Fruit", "Name of Fruit"]

你想要这个输出

["Name of Fruit 2": "Lemon", "Name of Fruit 0": "Apple", "Name of Fruit 1": "Banana"]

然后你可以使用这段代码

let dict = zip(fruits, keys).enumerate().reduce([String:String]()) { (var result, elm) -> [String:String] in
    let key = "\(elm.element.1) \(elm.index)"
    let value = elm.element.0
    result[key] = value
    return result
}

或此代码

assert(keys.count == fruits.count)
var dict = [String:String]()
for i in 0..<fruits.count {
    let key = "\(keys[i]) \(i)"
    let value = fruits[i]
    dict[key] = value
}