gpt4 book ai didi

foreach - SwiftUI - ForEach - 类型 '_' 没有成员 'name'

转载 作者:行者123 更新时间:2023-12-04 17:30:22 24 4
gpt4 key购买 nike

我正在尝试 ForEach 类内的字符串数组并收到错误:类型“_”没有成员“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)
}
}
}
}
}

最佳答案

首先你的模型需要是可修改的(所以使用 var 而不是 let)

struct StatisticItem: Codable {
var name: String
var startValue: Int
var modifier: Int
}

其次,TextField需要Binding,所以应该像下面这样

ForEach(Array(statistics.statList.enumerated()), id:\.1.name) { (i, stat) in
TextField("", text: self.$statistics.statList[i].name)
}

关于foreach - SwiftUI - ForEach - 类型 '_' 没有成员 'name',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60251035/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com