TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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 Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

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.