gpt4 book ai didi

swift - 标记闭包元素可变 Swift

转载 作者:行者123 更新时间:2023-11-28 11:36:32 25 4
gpt4 key购买 nike

我有 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/

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