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

Day 19: Challenge Day

Forums > 100 Days of SwiftUI

I couldn't wrap my head around converting the units that had different scales (meters, feet, etc.) so I took the easy way out and did the time conversion. Although I guess maybe Swift has some built-in functions for converting things (looking at other people's solutions to this)?

Originally I spent awhile trying to get the two pickers to get their value and label from one dictionary, but couldn't figure it out and just kept getting a bunch of weird errors in Xcode that I didn't really know how to fix.

So I ended up using an array of units, and then a dictionary with keys to match the units values. Took me awhile to then figure out how to treat that lookup as an optional, but once I got that working then it all seemed to click.

I'd be interested to know if there is a way to populate the pickers using just the unitsDisplay dictionary directly vs. my hack of the units array as well.

Took a bit of trial and error but seems to work fairly well in the end. I'd appreciate any feedback or suggestions anybody has.

Thanks. SwiftUI is fun so far :)

struct ContentView: View {
    @State private var inputUnit:Int = 1
    @State private var outputUnit:Int = 1
    @State private var inputNumber:Int = 1
    @FocusState private var inputNumberIsFocused: Bool

    let units = [1, 60, 3600, 86400]
    let unitsDisplay = [
        1 : "Seconds",
        60 : "Minutes",
        3600 : "Hours",
        86400 : "Days"
    ]

    var convertedNumber: Int {
        let converted = inputNumber * inputUnit / outputUnit;
        return converted
    }

    var body: some View {
        NavigationView {
            Form {
                Section {
                    TextField("Amount", value: $inputNumber, format: .number)
                        .keyboardType(.numberPad)
                        .focused($inputNumberIsFocused)
                } header: {
                    Text("Number to Convert")
                }

                Section {
                    Picker("Input Units", selection: $inputUnit) {
                        ForEach(units, id: \.self) {
                            if let label = unitsDisplay[$0] {
                                Text(label)
                            }
                        }
                    }
                    .pickerStyle(.segmented)
                } header: {
                    Text("Convert From")
                }

                Section {
                    Picker("Input Units", selection: $outputUnit) {
                        ForEach(units, id: \.self) {
                            if let label = unitsDisplay[$0] {
                                Text(label)
                            }
                        }
                    }
                    .pickerStyle(.segmented)
                } header: {
                    Text("Convert To")
                }

                Section {
                    Text(convertedNumber, format: .number)
                } header: {
                    Text("Converted Number")
                }
            }
            .navigationTitle("Convert It!")
            .toolbar {
                ToolbarItemGroup(placement: .keyboard) {
                    Spacer()

                    Button("Done") {
                        inputNumberIsFocused = false
                    }
                }
            }
        }
    }
}

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

1      

I'd be interested to know if there is a way to populate the pickers using just the unitsDisplay dictionary directly vs. my hack of the units array as well.

You can do this:

Picker("Input Units", selection: $inputUnit) {
    ForEach(Array(unitsDisplay.keys).sorted(), id: \.self) {
        Text(unitsDisplay[$0]!)
    }
}

(The force unwrap is fine here since we know the key exists in the dictionary.)

1      

Awesome! I figured there must be a simple way to do it I just couldn't figure out. I'll give that a try. Thank you!

1      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.