gpt4 book ai didi

ios - 闭包在方法 mapValues 中是如何工作的?

转载 作者:行者123 更新时间:2023-12-01 18:34:17 24 4
gpt4 key购买 nike

我试图理解 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返回一个字典“包含该字典的键以及由给定闭包转换的值。”
    我的问题是, colorIndex 的值到底是多少?在 data.mapValues { (colorIndex) -> UIColor in 中传递到闭包中?是来自 heatmap.plist ?我很困惑 String被传递到 date , date[dateString] 来自 colorFor(dateComponents: )功能,但 colorIndex是诠释。

    最佳答案

    原来,data是这样的:

    "2019.5.3" : 3
    "2019.5.5" : 4
    "2019.5.7" : 3
    假设你做了 data.mapValues(f) , 其中 f是一个函数,生成的字典将如下所示:
    "2019.5.3" : f(3)
    "2019.5.5" : f(4)
    "2019.5.7" : f(3)
    所以现在,字典的值类型变成了 f的返回类型。 ,而 key 类型保持不变。

    what exactly is the value colorIndex passed into the closure?


    它是 data 中的每个值.每个值都将被传递给闭包一次。
    为了更清楚地看到这一点,我写了一种可能的方式 mapValues可以实现:
    extension Dictionary {
    func myMapValues<T>(_ transform: (Value) throws -> T) rethrows -> [Key: T] {
    var retVal = [Key: T]()
    for entry in self {
    retVal[entry.key] = try transform(entry.value)
    }
    return retVal
    }
    }

    Is it from heatmap.plist?


    间接地,是的。局部变量 data的内容( [String: Int] )最初来自 heatmap.plist , 但是 mapValues直接在 data 上运行已经从文件中读取。

    I'm confused how a String is passed into data, data[dateString] from the colorFor(dateComponents: ) function, but colorIndex is Int.

    colorIndex在这里无关紧要。 colorIndex只是传递给 mapValues 的函数的函数参数的名称. mapValues此时已调用,并且字典的值已被转换。
    您可以通过 String进入 data因为 data字典有 String s 作为键。回想一下 mapValues不会更改 key 类型。请注意,此 data不同于局部变量 data .我说的是 lazy房产 data , 类型为 [String: UIColor] .

    关于ios - 闭包在方法 mapValues 中是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63238688/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com