BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

SwiftUI - Picker with variable data source

Forums > SwiftUI

Hello all, I am trying to make a picker (named Letters in the below example) with variable data source (lettersArray), where these data depends on selections of other picker (Numbers), I tried that through the didSet as per the below example, but it crashes. Any advice in that!

import SwiftUI

class Model: ObservableObject, Identifiable {
    var lettersArray = ["A", "B", "C"]
    var numArray = ["0", "1", "2", "3"]

    @Published var lettersIndx = 0

    @Published var numIndex = 0 {
        didSet{
            switch numIndex {
            case 0:
                lettersArray = ["A", "B", "C"]
            case 1:
                lettersIndx = 0
                lettersArray = ["A"]
            case 2:
                lettersIndx = 1
                lettersArray = ["B", "C"]
            default:
                lettersArray = ["A", "B", "C"]
            }
        }
    }
}

struct ContentView: View {
    @ObservedObject var model = Model()

    var body: some View {
        VStack{
            Spacer()
            Picker("Letters", selection: $model.lettersIndx) {
                ForEach(model.lettersArray.indices, id: \.self) { (index: Int) in
                    Text(self.model.lettersArray[index])
                }
            }.pickerStyle(WheelPickerStyle())

            Spacer()

            Picker("Numbers", selection: $model.numIndex) {
                ForEach(model.numArray.indices, id: \.self) { (index: Int) in
                    Text(self.model.numArray[index])
                }
            }
            .pickerStyle(WheelPickerStyle())

            Spacer()
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

2      

@aliabuahmadeh I don't see the crash. It is working for me

2      

@achuaswani ,

thanks for reply. it is crashing, at least once you move the Numbers Picker to number 2, and this message is received: Fatal error: Index out of range.

2      

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.