美文网首页
Swift enumerated函数

Swift enumerated函数

作者: NapoleonY | 来源:发表于2018-04-11 18:13 被阅读215次

概述

两个数组组合成一个字典

//数组
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"]
//字典
var scoreDatesDictionary = [
"7/12/15": [1,2,3,4]
"7/13/15": [5,6,7,8]
"7/14/15": [9]
]

解决方案

func enumFunc() {
        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 dates.enumerated() {
            dic[date] = (dic[date] ?? []) + [score[index]]
        }
        print("dic = \(dic)")
    }

备注:??操作符

a ?? b可以理解成

if a != nil {
  return a
} else {
  return b
}

//或者
a != nil ? a! : b

参考

  1. Combining 2 arrays into a dictionary in Xcode 6, swift?, with corresponding index values)

相关文章

网友评论

      本文标题:Swift enumerated函数

      本文链接:https://www.haomeiwen.com/subject/vorzhftx.html