【发布时间】:2020-08-04 00:34:02
【问题描述】:
我试图了解mapValues 方法在Calendar Heatmap 的以下代码中的工作原理。
- 首先,函数加载字典:
private func readHeatmap() -> [String: Int]? {
guard let url = Bundle.main.url(forResource: "heatmap", withExtension: "plist") else { return nil }
return NSDictionary(contentsOf: url) as? [String: Int]
}
heatmap.plist 是这样的键/值列表:
<key>2019.5.3</key>
<integer>3</integer>
<key>2019.5.5</key>
<integer>4</integer>
<key>2019.5.7</key>
<integer>3</integer>
- 使用上述函数初始化属性:
lazy var data: [String: UIColor] = {
guard let data = readHeatmap() else { return [:] }
return data.mapValues { (colorIndex) -> UIColor in
switch colorIndex {
case 0:
return UIColor(named: "color1")!
case 1:
return UIColor(named: "color2")!
case 2:
return UIColor(named: "color3")!
case 3:
return UIColor(named: "color4")!
default:
return UIColor(named: "color5")!
}
}
}()
- 最后,上面定义的
data属性用在下面的函数中:
func colorFor(dateComponents: DateComponents) -> UIColor {
guard let year = dateComponents.year,
let month = dateComponents.month,
let day = dateComponents.day else { return .clear}
let dateString = "\(year).\(month).\(day)"
return data[dateString] ?? UIColor(named: "color6")!
}
Apple 的文档指出 mapValues 返回一个字典“包含该字典的键以及由给定闭包转换的值。”
我的问题是,传递给data.mapValues { (colorIndex) -> UIColor in 闭包的值colorIndex 到底是什么?是来自heatmap.plist 吗?我很困惑 String 是如何从 colorFor(dateComponents: ) 函数传递到 date, date[dateString] 的,但 colorIndex 是 Int。
【问题讨论】: