我有一段代码试图将 Firestore 数据放入选择器中。我之前已经做到了,因此选择器将显示 Firestore 数据,但我无法选择它以在“选定 View ”中显示,因此我重写了代码并出现以下错误 "Initializer 'init(_: )' 要求 'getSchoolData' 符合 'StringProtocol' "
请原谅,这听起来像是一个愚蠢的问题,我似乎无法解决它。我的代码副本如下。我已经尝试了数周的时间,但不知所措,所以请善待,我是编码新手。
提前致谢
import SwiftUI
import Firebase
struct SchoolDetailsView: View {
let schoolData = [getSchoolData()]
@State var selectedSchool = 0
var body: some View {
VStack {
Form {
Section {
Picker(selection: $selectedSchool, label: Text("School Name")) {
ForEach(0 ..< schoolData.count) {
Text(self.schoolData[$0])
}
}
Text("Selected School: \(selectedSchool)")
}
}.navigationBarTitle("Select your school")
}
}
}
struct SchoolPicker_Previews: PreviewProvider {
static var previews: some View {
SchoolDetailsView()
}
}
class getSchoolData : ObservableObject{
@Published var datas = [schoolName]()
init() {
let db = Firestore.firestore()
db.collection("School Name").addSnapshotListener { (snap, err) in
if err != nil{
print((err?.localizedDescription)!)
return
}
for i in snap!.documentChanges{
let id = i.document.documentID
let name = i.document.get("Name") as! String
self.datas.append(schoolName(id: id, name: name))
}
}
}
}
struct schoolName : Identifiable {
var id : String
var name : String
}
最佳答案
您可以尝试以下方法:
struct SchoolDetailsView: View {
@ObservedObject var schoolData = getSchoolData() // make `@ObservedObject`/`@StateObject` instead of const array
@State var selectedSchool = "" // `schoolName.id` is of type String
var body: some View {
VStack {
Form {
Section {
Picker(selection: $selectedSchool, label: Text("School Name")) {
ForEach(schoolData.datas, id: \.id) { // choose whether you want to tag by `id` or by `name`
Text($0.name)
}
}
Text("Selected School: \(selectedSchool)")
}
}.navigationBarTitle("Select your school")
}
}
}
关于swift - 初始化器 'init(_:)' 要求 '' 符合 'StringProtocol' SwiftUI Picker with Firebase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64562976/