錯誤是:“包含控制流陳述句的閉包不能與結果構建器‘ViewBuilder ’一起使用”
這段代碼在這里作業......
if let a = array {
List(a, id: \.self) { item in
Text(item)
}
} else {
Text("Please click add button.")
}
但是這里的代碼(在底部的代碼塊中找到)沒有?怎么來的?
if let a = array {
for element in 0...a.count-1 {
Text(a[element])
}
} else {
Text("Please click add button.")
}
源代碼...
@State var array:[String]? = nil
@State var message = ""
var body: some View {
VStack {
Text(message)
.font(.body)
HStack {
Button("Set to nill") {
array = nil
}.padding()
Button("Add strings") {
array = ["String 1", "String 2", "String 3"]
}.padding()
}
//Why doesn't the below work?
if let a = array {
for element in 0...a.count-1 {
Text(a[element])
}
} else {
Text("Please click add button.")
}
}
}
}
uj5u.com熱心網友回復:
所有的 SwifUI 視圖構建器都是構建結構。當您在 for 回圈中創建這樣的結構時,該結構在超出回圈范圍時將被洗掉。
SwiftUI 使用 ForEach 和 List 之類的東西來代替像 for 這樣的流控制結構,但仍然創建嵌套結構。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/336402.html
