【发布时间】:2021-10-20 14:11:40
【问题描述】:
在我正在编写的 swiftUI 视图中,我需要使用 ForEach,访问列表的每个元素和它的索引。我能找到的大部分信息都说使用.enumerated(),如ForEach(Array(values.enumerated()), id: \.offset) { index, value in }
但是,当我尝试这样做时,我认为:
/// A popover displaing a list of items.
struct ListPopover: View {
// MARK: Properties
/// The array of vales to display.
var values: [String]
/// Whether there are more values than the limit and they are concatenated.
var valuesConcatenated: Bool = false
/// A closure that is called when the button next to a row is pressed.
var action: ((_ index: Int) -> Void)?
/// The SF symbol on the button in each row.
var actionSymbolName: String?
// MARK: Initializers
init(values: [String], limit: Int = 10) {
if values.count > limit {
self.values = values.suffix(limit - 1) + ["\(values.count - (limit - 1)) more..."]
valuesConcatenated = true
} else {
self.values = values
}
}
// MARK: Body
var body: some View {
VStack {
ForEach(Array(values.enumerated()), id: \.offset) { index, value in
HStack {
if !(index == values.indices.last && valuesConcatenated) {
Text("\(index).")
.foregroundColor(.secondary)
}
Text(value)
Spacer()
if action != nil && !(index == values.indices.last && valuesConcatenated) {
Spacer()
Button {
action!(index)
} label: {
Image(systemName: actionSymbolName ?? "questionmark")
}
.frame(alignment: .trailing)
}
}
.if((values.count - index) % 2 == 0) { view in
view.background(
Color(.systemGray5)
.cornerRadius(5)
)
}
}
}
}
}
我在var body: some View { 线上收到错误The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions
我还注意到这段代码会导致一些其他问题,比如让 Xcode 自动完成变得非常慢。
有什么想法可以解决这个问题吗?这似乎是一个非常简单的视图,我认为我正在做我应该做的ForEach。
谢谢!
【问题讨论】:
-
在 12.5 或 13.0b4 上无法重现。过去,我注意到 Xcode 有时在 SwiftUI 中使用
&&进行布尔评估时会出现问题,因此我会考虑为那些可以拆分的函数构建辅助函数。 -
不要不要使用
id作为\.offset- 改用\.element。当元素发生变化时,使用偏移会导致问题。
标签: swift swiftui swiftui-foreach swift-compiler