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

SOLVED: I guess this code is silly, but how to make it smarter? 🤣 #Bindings #UnitConversion

Forums > SwiftUI

Ok, very simple: Three TextFields with Celsius, Fahrenheit and Kelvin. If you change one, the others follow. I'd like to discuss, how to code this smarter. Please join the discussion, if you like!

Problems:

  • The values are calculated several times
  • so many Bindings
import SwiftUI

enum UnitSymbol: String {
    case celsius = "° C"
    case fahrenheit = "° f"
    case kelvin = "K"
}

struct ContentView: View {
    @State private var celsius      = Measurement(value: 0, unit: UnitTemperature.celsius)
    @State private var fahrenheit   = Measurement(value: 0, unit: UnitTemperature.fahrenheit)
    @State private var kelvin       = Measurement(value: 0, unit: UnitTemperature.kelvin)

    var body: some View {
        Form {
            BoxView(symbol: .celsius, celsius: $celsius, fahrenheit: $fahrenheit, kelvin: $kelvin)
            BoxView(symbol: .fahrenheit, celsius: $celsius, fahrenheit: $fahrenheit, kelvin: $kelvin)
            BoxView(symbol: .kelvin, celsius: $celsius, fahrenheit: $fahrenheit, kelvin: $kelvin)
        }
        .ignoresSafeArea(.keyboard)
    }
}

struct BoxView: View {
    var symbol: UnitSymbol

    @Binding var celsius:       Measurement<UnitTemperature>
    @Binding var fahrenheit:    Measurement<UnitTemperature>
    @Binding var kelvin:        Measurement<UnitTemperature>

    var body: some View {
        HStack {
                TextField("Enter value:", value: symbol == .celsius ? $celsius.value : symbol == .fahrenheit ? $fahrenheit.value : $kelvin.value, format: .number)
                    .font(.largeTitle)
                    .keyboardType(.decimalPad)
                    .onChange(of: celsius) { _ in
                        fahrenheit      = celsius.converted(to: .fahrenheit)
                        kelvin          = celsius.converted(to: .kelvin)
                    }
                    .onChange(of: fahrenheit) { _ in
                        celsius         = fahrenheit.converted(to: .celsius)
                        kelvin          = fahrenheit.converted(to: .kelvin)
                    }
                    .onChange(of: kelvin) { _ in
                        celsius         = kelvin.converted(to: .celsius)
                        fahrenheit      = kelvin.converted(to: .kelvin)
                    }

                Text(symbol.rawValue)
                    .font(.largeTitle)
                    .italic()

            }
        }
    }

2      

Here's one way to do it. This uses just a single Measurement<UnitTemperature> stored in kelvin and converts it as needed for the individual TextFields. That way we don't have to manually convert each time one of the TextFields changes, but can rely on the Binding mechanism to do it all for us.

import SwiftUI

struct TemperatureView: View {
    @State private var temperature = Measurement(value: .zero, unit: UnitTemperature.kelvin)
    //we only need to store this temperature once
    //we can then convert it to other scales as needed

    var body: some View {
        Form {
            TemperatureBox(unit: .celsius, temperature: $temperature)
            TemperatureBox(unit: .fahrenheit, temperature: $temperature)
            TemperatureBox(unit: .kelvin, temperature: $temperature)
        }
        .ignoresSafeArea(.keyboard)
    }
}

struct TemperatureBox: View {
    let unit: UnitTemperature
    @Binding var temperature: Measurement<UnitTemperature>

    //create an ad hoc Binding to convert the base temperature
    //  to a Double we can hook into the TextField
    var formattedTemperature: Binding<Double> {
        Binding(
            get: {
                temperature.converted(to: unit).value
            },
            set: { newValue in
                //remember we are storing the temperature as kelvin
                $temperature.wrappedValue = Measurement(value: newValue, unit: unit).converted(to: .kelvin)
            }
        )
    }

    var body: some View {
        HStack {
            TextField("Enter value", value: formattedTemperature, format: .number)
                .keyboardType(.decimalPad)
            Text(unit.symbol)
                .italic()
        }
        .font(.largeTitle)
    }
}

3      

Wow! Thank you for this elegant solution.

While experimenting with your code, I tried to change this line:

$temperature.wrappedValue = Measurement(value: newValue, unit: unit).converted(to: .kelvin)

to

temperature = Measurement(value: newValue, unit: unit).converted(to: .kelvin)

It's still working. Where is the difference?

2      

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.