swift - 标记闭包元素可变 Swift

标签 swift

我有 2 个结构,第一个是:

struct LineData {

    init (name: String,
          colorValue: String,
          values: [Int]){
        self.name = name
        self.colorValue = colorValue
        self.values = values
    }

    private var cachedMaxValue: Int? = nil
    let name: String
    let colorValue: String
    let values: [Int]

    // describe max value for Y axis for specific Line
    mutating func maxValue() -> Int{
        if let cached = cachedMaxValue {
            return cached
        }
        self.cachedMaxValue = values.max()
        return cachedMaxValue ?? 0
    }
}

第二个是 LineData 结构数组:

struct CharData {

    init(xAxis: XAxis,
         lines: [LineData]){
        self.xAxis = xAxis
        self.lines = lines
    }

    private var cachedMaxValue: Int? = nil

    var xAxis: XAxis
    var lines: [LineData]

    // describe max value for Y axis among lines
    func maxValue() -> Int{

        var maxValues: [Int] = []
        lines.forEach{it in
            maxValues.append(it.maxValue())
        }

        return 0
    }
}

上面的代码无法编译,因为结构 CharData 的方法 maxValues 出错。它说 Cannot use mutating member on immutable value: 'it' is a 'let' constant

我想要的是,遍历一组行,并在其中的最大值中找到更大的值。

最佳答案

既然 lines 是一个普通的数组,那么简单的怎么样:

    for i in 0..<lines.count {
        maxValues.append(lines[i].maxValue())
    }

也许不如 Swifty,但没有任何东西被复制。优化器应该为您提供与 forEach 几乎相同的性能。

关于swift - 标记闭包元素可变 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55151670/

相关文章:

swift - 如何使用 displayName 更新用户

ios - 调整视频大小并保持 1 :1 scale

ios - 如何创建具有复杂内容的 UITableViewCells 以保持滚动流畅

ios - ELCImagePickerController 不会 swift 返回到 viewController

ios - 未显示 UITableViewCell 中的 UILabel

java - Google map API 支持卡车导航吗?

swift - 无法读取 PNG 文件的 IHDR block

SwiftUI:如何自定义仅适用于 iPad 的工作表?

ios - 如何将音频添加到 TableView 中的 UIButtons?

ios - WKWebView 在本地通知上打开 URL