【发布时间】:2020-08-05 17:52:13
【问题描述】:
我在 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
提前谢谢你。
【问题讨论】:
标签: ios if-statement foreach swiftui