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

Measurement framework ounces in cup question

Forums > Swift

Why does the Measurement framework not return exactly 8 fluid ounces when I convert one cup? I can't seem to find any reference (in or out of Apple's developer documentation) for a volumetric cup not equaling exactly 8 fluid ounces.

import SwiftUI

let testOneCup = Measurement(value: 1, unit: UnitVolume.cups)
let testOunces = testOneCup.converted(to: UnitVolume.fluidOunces)
print(testOunces)

It prints: 8.11537356078922 fl oz

2      

Well, it seems that the Unitvolume.cups is a "legal cup" which is indeed 8.11537 ounces. It seems that a "legal cup" is a cup that in the US is used for nutritional values such as shown on a food label. Odd.

2      

Just swinging back to post my "SOLUTION" if you will:

Per Apple's UnitVolume documentation, the .cups Unit has a coefficient of 0.24 (base is Liters for all UnitVolume unit types) and .fluidOunces has a coefficient of 0.0295735, I simply multiplied 0.0295735 * 8 (i.e., one ounce times eight), I created a custom unit (symbol: cupsUSKitchen) and gave it a coeffient of 0.236588 and that did the trick.

import SwiftUI

let cupsUSKitchen = UnitVolume(symbol: "cupsUSKitchen", converter: UnitConverterLinear(coefficient: 0.236588))

let myCups = Measurement(value: 1, unit: cupsUSKitchen)
let testOunces = myCups.converted(to: .fluidOunces)

Now, when I convert 1 cupUSKitchen into fluidOunces, it indeed returns 8 fl oz.

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.