簡體   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