我有一段代码试图在选择器中放置Firestore数据。我之前已经这样做过,以便选择器将显示Firestore数据,但是我无法选择它以显示在“选定的视图”中,因此我重写了代码并出现以下错误“ 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
}
答案 0 :(得分:0)
您可以尝试以下操作:
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")
}
}
}