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

Day 19. Unit conversion. Units display.

Forums > 100 Days of SwiftUI

@Borys  

I have a question about measurements. I have these values

var inputMeasurement: Measurement<UnitLength> {
    Measurement(value: Double(value) ?? 0, unit: units[inputUnitIndex])
}

var outputMeasurement: Measurement<UnitLength> {
    inputMeasurement.converted(to: units[outputUnitIndex])
}

var input: String {
    "\(inputMeasurement)"
}

var result: String {
    "\(outputMeasurement)"
}

I'm curious why when I'm trying to display the result with

Text("\(inputMeasurement) equals \(outputMeasurement)")

I'm getting

<NSMeasurement: 0x...> value: 0.000000 unit: m, equals <NSMeasurement: 0x...> value: 0.000000 unit: km

but with

Text("\(input) equals \(result)")

I'm getting

0.0 m equals 0.0 km

Is there a way to display measurement as a string without creating new variable?

3      

I am not sure why it displays that, could be because it's a computed property... maybe?

In any case, you should be able to use inputMeasurement.value to display the number and not need another property.

Also, if you would like more insights, there was a discussion over here:

https://www.hackingwithswift.com/forums/100-days-of-swiftui/day-19-challenge-is-there-a-better-way-for-this-code/2682

3      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.