繁体   English   中英

Initializer 'init(_:)' 要求 '' 符合 'StringProtocol' SwiftUI Picker with Firebase

[英]Initializer 'init(_:)' requires that '' conform to 'StringProtocol' SwiftUI Picker with Firebase

我有一段代码,我试图将 Firestore 数据放置在选择器中。 我之前已经做了,以便选择器将显示 Firestore 数据,但我无法选择它以显示在“选定视图”中,因此我重写了代码并出现以下错误“Initializer 'init(_:)' requires '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")
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM