[英]Initializer 'init(_:)' requires that '' conform to 'StringProtocol' SwiftUI Picker with Firebase
I have a piece of code where I'm trying to place Firestore data within a picker.我有一段代码,我试图将 Firestore 数据放置在选择器中。 I have made it previously so that the picker will show the Firestore data, but I am unable to select it to show in the 'selected view' therefore I rewrote the code and have the following error "Initializer 'init(_:)' requires that 'getSchoolData' conform to 'StringProtocol' "
我之前已经做了,以便选择器将显示 Firestore 数据,但我无法选择它以显示在“选定视图”中,因此我重写了代码并出现以下错误“Initializer 'init(_:)' requires 'getSchoolData' 符合 'StringProtocol'"
Please excuse that it may sound like a daft question I just can't seem to solve it.请原谅这听起来像是一个愚蠢的问题,我似乎无法解决它。 A copy of my code is below.
我的代码的副本如下。 I have tried working on this for weeks but at a loss so please be kind, I'm new to coding.
我已经尝试了几个星期,但不知所措,所以请善待,我是编码新手。
Thanks in advance,提前致谢,
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
}
You may try the following:您可以尝试以下操作:
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")
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.