将2个数组组合成Xcode 6中的字典,swift ?,具有相应的索引值)

时间:2015-07-12 13:40:16

标签: swift dictionary

在我的应用程序中,我有2个正在使用的数组,一个将得分值存储为整数的数组,另一个以#34; mm / dd / yy"格式存储日期的数组。这些数组被连续地追加,并且这些数组的索引彼此对应,例如,日期数组的索引0对应于得分数组的索引0。我希望在第二个屏幕加载时(这些是全局变量)将这些数组转换为字典。例如,这些是每个数组中的值类型。

score == [1,2,3,4,5,6,7,8,9]
dates == ["7/12/15","7/12/15","7/12/15","7/12/15","7/13/15","7/13/15","7/13/15","7/13/15","    7/14/15"]

我想要发生的是,在viewDidLoad()上,这会被创建。

var scoreDatesDictionary = [
"7/12/15": [1,2,3,4]
"7/13/15": [5,6,7,8]
"7/14/15": [9]
]

本质上,两个数组具有相应的值,(firstArray [0])对应于(secondArray [0])。我试图在secondArray(日期)中使相同的字符串在字典中与其对应的索引值匹配。我可能没有多大意义,但我提供的示例代码应该可行。我花了很多时间来处理这个问题,但我无法找到解决方案。

3 个答案:

答案 0 :(得分:1)

    let  score = [1,2,3,4,5,6,7,8,9,]
    let  dates = ["7/12/15","7/12/15","7/12/15","7/12/15","7/13/15","7/13/15","7/13/15","7/13/15"," 7/14/15"]
    var dic = [String:[Int]]()
    for var index=0;index < dates.count; index++ {
        let key = dates[index];
        var value = dic[key]
        if value == nil{
            dic[key] = [score[index]]
        }else{
            value!.append(score[index])
            dic[key] = value
        }
    }
    println(dic)

这将记录

[7/12/15: [1, 2, 3, 4],  7/14/15: [9], 7/13/15: [5, 6, 7, 8]]

答案 1 :(得分:1)

func zipToDict<
  S0 : SequenceType,
  S1 : SequenceType where
  S0.Generator.Element : Hashable
  >(keys: S0, values: S1) -> [S0.Generator.Element:[S1.Generator.Element]] {
    var dict: [S0.Generator.Element:[S1.Generator.Element]] = [:]
    for (key, value) in zip(keys, values) {
      dict[key] = (dict[key] ?? []) + [value]
    }
    return dict
}

let score = [1,2,3,4,5,6,7,8,9]
let dates = ["7/12/15","7/12/15","7/12/15","7/12/15","7/13/15","7/13/15","7/13/15","7/13/15","    7/14/15"]

print(zipToDict(dates, score)) // [7/12/15: [1, 2, 3, 4], 7/14/15: [9], 7/13/15: [5, 6, 7, 8]]

答案 2 :(得分:0)

关闭@Leo的正确答案,这是一个使用enumerate nil合并运算符 ??的版本来做更多干净地:

对于 Swift 1.2:

let score = [1,2,3,4,5,6,7,8,9]
let dates = ["7/12/15","7/12/15","7/12/15","7/12/15","7/13/15","7/13/15","7/13/15","7/13/15"," 7/14/15"]
var dic = [String:[Int]]()

for (index, date) in enumerate(dates) {
    dic[date] = (dic[date] ?? []) + [score[index]]
}
print(dic)  // prints "[7/12/15: [1, 2, 3, 4],  7/14/15: [9], 7/13/15: [5, 6, 7, 8]]"

对于 Swift 2.0 ,您需要改为使用dates.enumerate()