我在iOS SwiftUI(Xcode版本11.6)的ForEach内部有一个“if”,它可以正常工作。
struct ContentView: View {
var body: some View {
List {
ForEach(0 ..< 10) {(i: Int) in
if i % 2 == 0 {
Text(String(i))
}
}
}
}
}
现在,我想做同样的事情,但是要使用字符串数组而不是Ints的半开范围。struct ContentView: View {
let states: [String] = [
"Alabama",
"Alaska",
"Arizona",
"Arkansas",
"California"
];
var body: some View {
List {
ForEach(states, id: \.self) {(state: String) in
if state.hasPrefix("Al") {
Text(state)
}
}
}
}
}
我从此ForEach得到的错误消息是Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols
出了什么问题?我很困惑,因为Apple的SwiftUI教程在第3部分第1步的ForEach中有一个“if”https://developer.apple.com/tutorials/swiftui/handling-user-input
先感谢您。
最佳答案
您可以尝试以下方法:
struct ContentView: View {
...
var body: some View {
List {
ForEach(states, id: \.self) { state in
self.stateView(state: state)
}
}
}
@ViewBuilder
func stateView(state: String) -> some View {
if state.hasPrefix("Al") {
Text(state)
}
}
}
这样,您的代码也可能更具可读性。
关于ios - iOS SwiftUI中ForEach内部的if语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63270850/