【发布时间】:2020-05-31 17:04:46
【问题描述】:
我正在尝试 ForEach 在类内部的字符串数组上并收到错误:
Type '_' has no member 'name'
我正在尝试模拟我在本教程中阅读的内容,但不明白为什么我的编译失败。 https://www.hackingwithswift.com/books/ios-swiftui/working-with-identifiable-items-in-swiftui
struct StatisticItem: Codable {
let name: String
let startValue: Int
let modifier: Int
}
class Statistics: ObservableObject {
let statisticsNames = ["One", "Two"]
@Published var statList: [StatisticItem]
init() {
self.statList = [];
for statisticsName in statisticsNames {
self.statList.append(StatisticItem(name: statisticsName, startValue: Int.random(in: 20 ... 100), modifier: 0))
}
}
}
struct ContentView: View {
@ObservedObject var statistics = Statistics()
var body: some View {
Form {
List {
// Error shows up on this line: Type '_' has no member 'name'
ForEach(statistics.statList, id:\.name) { stat in
TextField(stat.name)
}
}
}
}
}
【问题讨论】:
-
我认为问题不是因为
ForEach,而是因为TextField,试着换个简单的Text看看会发生什么