NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

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

   

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.

   

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.

   

Hacking with Swift is sponsored by Paw

SPONSORED Use Paw to build, test and describe web APIs. Paw has a lightning fast native macOS interface to compose requests, collaborate in real-time on API specs, and generate client code for your applications. You can import and export API definitions.

Discover Paw for Mac

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

Not logged in

Log in
 

Link copied to your pasteboard.