简体   繁体   中英

When using a swiftui picker with an array of options. How can I save the selected option rather than the index value to Cloud Firestore?

I'd like to be able to access and use the location. Currently only the index value from the picker is being saved to Cloud Firestore.

Here is the picker:

Picker(selection: $viewModel.injury.locationIndex, label: Text("General Location")) {
  ForEach(0 ..< locationOptions.count) {
    Text(self.locationOptions[$0])
}

Here is the array:

var locationOptions = ["🤕 Head", "🦺 Chest", "💪 Right Arm", "💪 Left Arm", "🤚 Right Hand", "✋ Left Hand", "🩲 Waist", "🦵 Right Leg", "🦵 Left Leg", "🦶 Right Foot", "🦶 Left Foot"]

The locationIndex is successfully uploaded to Cloud Firestore:

import SwiftUI
import Firebase

class InjuryViewModel: ObservableObject {
    
    @Published var injury: Injury = Injury(id: "", userId: "", specificLocation: "", comment: "", active: false, injuryDate: Date(), exercises: "", locationIndex: 0)
    
    
    private var db = Firestore.firestore()
    
    func addInjury(injury: Injury) {
        
        do{
            var addedInjury = injury
            addedInjury.userId = Auth.auth().currentUser?.uid
            let _ = try db .collection("injuries").addDocument(from: addedInjury)
        }
        catch {
            print(error)
        }
        
        
    }
    
    func save () {
        addInjury(injury: injury)
    }
    
}

The selection and identifier of Picker have to be same type. So you would have something like

Picker(selection: $viewModel.injury.specificLocation, label: Text("General Location")) {
  ForEach(locationOptions, id: \.self) {
    Text($0)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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