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

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?

1      

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

1      

Hacking with Swift is sponsored by Fernando Olivares

SPONSORED Fernando's book will guide you in fixing bugs in three real, open-source, downloadable apps from the App Store. Learn applied programming fundamentals by refactoring real code from published apps. Hacking with Swift readers get a $10 discount!

Read the book

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.