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

SOLVED: How can I link a Picker to a Dictionary value?

Forums > SwiftUI

I am trying to do it in the way shown below, but the Picker values never change from zero.

struct ContentView: View {
    enum PetType: String, CaseIterable, Identifiable {
        case dog = "🐢", cat = "🐱", fish = "🐟"

        var id: RawValue {
            self.rawValue
        }
    }

    @State private var petQuantities: [PetType: Int] = [.dog: 0, .cat: 0, .fish: 0]

    var body: some View {
        VStack {
            Form {
                ForEach(PetType.allCases) {
                    Picker("\($0.rawValue)", selection: $petQuantities[$0]) {
                        ForEach(0..<101) {
                            Text("\($0)")
                        }
                    }
                }
            }

            List {
                ForEach(PetType.allCases) {
                    Text(String(repeating: $0.rawValue, count: petQuantities[$0]!))
                }
            }
        }
    }
}

   

I found the solution, and I just had to change the Picker values to use a tag with an optional Int?

So now the Picker code looks like this

Picker("\($0.rawValue)", selection: $petQuantities[$0]) {
    ForEach(0..<101) {
        Text("\($0)").tag($0 as Int?)
    }
}

   

Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

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

Reply to this topic…

You need to create an account or log in to reply.

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.