NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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 {
            switch numIndex {
            case 0:
                lettersArray = ["A", "B", "C"]
            case 1:
                lettersIndx = 0
                lettersArray = ["A"]
            case 2:
                lettersIndx = 1
                lettersArray = ["B", "C"]
                lettersArray = ["A", "B", "C"]

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

    var body: some View {
            Picker("Letters", selection: $model.lettersIndx) {
                ForEach(model.lettersArray.indices, id: \.self) { (index: Int) in


            Picker("Numbers", selection: $model.numIndex) {
                ForEach(model.numArray.indices, id: \.self) { (index: Int) in


struct ContentView_Previews: PreviewProvider {
    static var previews: some View {


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


@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.


Hacking with Swift is sponsored by Judo

SPONSORED Let’s face it, SwiftUI previews are limited, slow, and painful. Judo takes a different approach to building visually—think Interface Builder for SwiftUI. Build your interface in a completely visual canvas, then drag and drop into your Xcode project and wire up button clicks to custom code. Download the Mac App and start your free trial today!

Try now

Sponsor Hacking with Swift and reach the world's largest Swift community!

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.