UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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]!))
                }
            }
        }
    }
}

1      

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?)
    }
}

1      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.