Post

Replies

Boosts

Views

Activity

Reply to SwiftUI and Measurement
Hi Cyrille, I just ran across this post, and if you haven't figured it out yet (or anyone else who finds this) the reason it's not working like you want is that @State cannot be used very well on complex data types. @State doesn't know which part of the value is changing. Anyway, the best way to overcome situations like this is to encapsulate your complex struct into a class and then call it as a @StateObject instead. See the following: class MyDistance: ObservableObject {     @Published var distance: Measurement<UnitLength>     init() {         distance = Measurement<UnitLength>(value: 13.37, unit: .meters)     } } struct ContentView: View {     @StateObject var distance = MyDistance()     var body: some View {         VStack {             Text("\(distance.distance.formatted(.measurement(width: .abbreviated, usage: .asProvided, numberFormatStyle: .number)))")             Button("Convert to cm") { print("Convert to cm");                 distance.distance = distance.distance.converted(to: .centimeters)             }             Button("Convert to m")  { print("Convert to m");                   distance.distance = distance.distance.converted(to: .meters)             }             Button("Convert to km") { print("Convert to km");                  distance.distance = distance.distance.converted(to: .kilometers)             }         }         .frame(minWidth: 300)         .padding()     } } I hope you find this useful.
Jan ’23