提问人:Peter Rice 提问时间:9/2/2023 最后编辑:Ken WhitePeter Rice 更新时间:9/2/2023 访问量:106
如何存储变量的值并在下一次 for 循环迭代中使用它们
How to store value of variables and use them in the next for loop iteration
问:
这是包含 150 行的表的第 2 到第 7 列,我将其分隔到一个新文件中,以便于阅读和维护。 在 for 循环中,变量应更新并存储,以便在逻辑运行后的下一次循环迭代中使用;但现在变量在一次迭代后被重置。 如何让变量可以存储到下一次循环迭代中?
import SwiftUI
class StockSymbol1Data: ObservableObject {
let secondaryRally = 1
let naturalRally = 2
let upwardTrend = 3
let downwardTrend = 4
let naturalReaction = 5
let secondaryReaction = 6
@Published var currentColumn: Double?
@Published var lastUpwardTrend: Double?
@Published var lastSecondaryRally: Double?
@Published var lastSecondaryReaction: Double?
@Published var lastNaturalRally: Double?
@Published var lastNaturalReaction: Double?
@Published var lastDownwardTrend: Double?
@Published var blackLineDownwardTrend: Double?
@Published var blackLineNaturalRally: Double?
@Published var redLineUpwardTrend: Double?
@Published var redLineNaturalReaction: Double?
}
struct StockSymbol1ColumnView: View {
let close1: Double
let headers: [String]
let scrollViewWidth: CGFloat
let priceMovePts: Double = 6
let furtherPriceMovePts: Double = 3
@ObservedObject var stockSymbol1Data: StockSymbol1Data
var body: some View {
ForEach(0..<6, id: \.self) { columnIndex in
let columnClose: Double? = {
switch columnIndex {
case 0:
// Apply your rule here for Secondary Rally column
return stockSymbol1Data.lastSecondaryReaction == close1 ? close1 : nil
case 1:
// Apply your rule here for Natural Rally column
return stockSymbol1Data.lastNaturalRally == close1 ? close1 : nil
case 2:
// Apply your rule here for Upward Trend column
return stockSymbol1Data.lastUpwardTrend == close1 ? close1 : nil
case 3:
// Apply your rule here for DownwardTrend column
return stockSymbol1Data.lastDownwardTrend == close1 ? close1 : nil
case 4:
// Apply your rule here for NaturalReaction column
return stockSymbol1Data.lastNaturalReaction == close1 ? close1 : nil
case 5:
// Apply your rule here for Secondary Reaction column
return stockSymbol1Data.lastSecondaryReaction == close1 ? close1 : nil
return nil
}
}()
let textColor: Color = {
switch columnIndex {
case 2:
// Change text color for Upward Trend column to black
return .black
case 3:
// Change text color forDownward Trend column to red
return .red
default:
return .gray
}
}()
Text(columnClose != nil ? "\(columnClose ?? 0.0)" : "")
.frame(width: scrollViewWidth / CGFloat(headers.count), height: 15)
.border(Color.gray, width: 2)
.padding(.horizontal, 5)
.foregroundColor(textColor)
}
}
}
我试过添加 Self。方法或其他方法,但新的循环迭代只是重置变量,无法获取上一个循环的结果和更新。我希望变量在一次循环迭代中更新,并且可以在随后的循环迭代中引用。
答: 暂无答案
上一个:变量仅在第二次运行宏后获取值
评论
struct
ForEach