WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

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

   

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

   

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!

   

Save 50% in my Black Friday sale.

SAVE 50% To celebrate WWDC22, all our books and bundles are half price, 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!

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.