Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork5
Xcode Playground Sample Code for the Flight School Guide to Swift Numbers
License
Flight-School/Guide-to-Swift-Numbers-Sample-Code
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation

This repository contains sample code used in theFlight School Guide to Swift Numbers.
Chapter 1 is a conceptual deep-dive intohow numbers work on computers in generaland in Swift specifically.
You know how floating-point arithmeticsometimes produces unexpected results,like0.1 + 0.2 != 0.3?(If not, go ahead and read thefirst chapter for free!)
This sample code implements an "approximately equals" operator (==~)for floating-point number types.
0.1+0.2==0.3 // false0.1+0.2==~0.3 // true(0.1+0.2).isApproximatelyEqual(to:0.3, within:.ulpOfOne) // true
Normally, you can't tell the difference betweennan andsignalingNaN.That's because Swift doesn't expose the floating-point environmentin its standard library.
We can still access it fromDarwin, though.And that's what this playground demonstrates:
do{trydetectingFloatingPointErrors(flags:.invalid){Double.signalingNaN+1}}catch{print("Error:\(error)")}
Chapter 2 is all about number formatting.The sample code in this chapter offers a comprehensive surveyof the various formatting styles ofNumberFormatter,and how they work in different locales.
letformatter=NumberFormatter()formatter.string(for:4) // 4formatter.numberStyle=.spellOutformatter.string(for:4) // four
letformatter=NumberFormatter()formatter.numberStyle=.ordinalformatter.string(for:1) // 1st
letformatter=NumberFormatter()formatter.numberStyle=.decimalformatter.string(for:1234567.89)1,234,567.89
letformatter=NumberFormatter()formatter.usesSignificantDigits=trueformatter.maximumSignificantDigits=2formatter.string(from:123) // 120formatter.string(from:123456) // 120000formatter.string(from:123.456) // 120formatter.string(from:1.230000) // 1.2formatter.string(from:0.00123) // 0.0012
letformatter=NumberFormatter()formatter.usesSignificantDigits=false // defaultformatter.minimumIntegerDigits=4formatter.minimumFractionDigits=2formatter.string(from:123) // 0123.00formatter.string(from:123456) // 123456.00formatter.string(from:123.456) // 0123.46formatter.string(from:1.230000) // 0001.23formatter.string(from:0.00123) // 0000.00
letformatter=NumberFormatter()formatter.numberStyle=.decimalformatter.maximumFractionDigits=1letnumbers=[1.2,1.22,1.25,1.27,-1.25]letmodes:[NumberFormatter.RoundingMode]=[.ceiling,.floor,.up,.down,.halfUp,.halfDown,.halfEven]formodein modes{ formatter.roundingMode= modefornumberin numbers{ formatter.string(for: number)}}
letformatter=NumberFormatter()formatter.numberStyle=.scientificformatter.string(for:12345.6789) // 1.23456789E4
letformatter=NumberFormatter()formatter.numberStyle=.percentformatter.string(for:0.12) // 12%
letformatter=NumberFormatter()letidentifiers=["en-US","en-GB","de-DE","ja-JP"]letstyles:[NumberFormatter.Style]=[.currency,.currencyAccounting,.currencyISOCode,.currencyPlural]forstylein styles{ formatter.numberStyle= styleforidentifierin identifiers{ formatter.locale=Locale(identifier: identifier) formatter.string(for:1234.567)}}
letformatter=NumberFormatter()formatter.numberStyle=.decimal// Format with thousands and decimal separator// that rounds to the nearest five tenthsformatter.format="#,##0.5"formatter.locale=Locale(identifier:"en-US")formatter.string(for:1234.567) // 1,234.5formatter.locale=Locale(identifier:"fr-FR")formatter.string(for:1234.567) // 1 234,5
Chapter 3 shows the correct way to represent and work with money in code.
letprices:[Money<USD>]=[2.19,5.39,20.99,2.99,1.99,1.99,0.99]letsubtotal= prices.reduce(0.00,+)lettax=0.08* subtotallettotal= subtotal+ tax // $39.45
letEURtoUSD=CurrencyPair<EUR,USD>(rate:1.17) // as of June 1st, 2018leteuroAmount:Money<EUR>=123.45letdollarAmount=EURtoUSD.convert(euroAmount) // $144.44
Chapter 4 covers Foundation's units and measurements APIs.
letlengthOfRoom=Measurement<UnitLength>(value:8, unit:.meters)letdistanceToAirport=Measurement<UnitLength>(value:16, unit:.kilometers)letformatter=MeasurementFormatter()formatter.unitOptions=.naturalScaleformatter.string(from: lengthOfRoom) // 26.247 ftformatter.string(from: distanceToAirport) // 9.942 mi
letingotMass=Measurement<UnitMass>(value:400, unit:.ouncesTroy)letformatter=MeasurementFormatter()formatter.unitOptions=.providedUnitformatter.string(from: ingotMass) // 400 oz t
letbarometerReading=Measurement<UnitPressure>(value:29.9, unit:.inchesOfMercury)letpressureInMillibars= barometerReading.converted(to:.millibars)letformatter=MeasurementFormatter()formatter.unitOptions=.providedUnitformatter.numberFormatter.usesSignificantDigits=trueformatter.numberFormatter.maximumSignificantDigits=3formatter.string(from: pressureInMillibars) // 1,010 mbar
lettemperatureInF=Measurement<UnitTemperature>(value:72, unit:.fahrenheit)lettemperatureInC=Measurement<UnitTemperature>(value:20.5, unit:.celsius)letformatter=MeasurementFormatter()formatter.locale=Locale(identifier:"en-US")formatter.string(from: temperatureInF) // 72°Fformatter.string(from: temperatureInC) // 68.9°Fformatter.locale=Locale(identifier:"fr-FR")formatter.string(from: temperatureInF) // 22,222 °Cformatter.string(from: temperatureInC) // 20,5 °Cformatter.unitOptions=.temperatureWithoutUnitformatter.locale=Locale(identifier:"en-US")formatter.string(from: temperatureInF) // 72°formatter.string(from: temperatureInC) // 20.5° (!)formatter.locale=Locale(identifier:"fr-FR")formatter.string(from: temperatureInF) // 72° (!)formatter.string(from: temperatureInC) // 20,5°
letloggedFlyingTime=Measurement<UnitDuration>(value:220, unit:.hours)letformatter=DateComponentsFormatter()formatter.allowedUnits=[.day]formatter.unitsStyle=.fullformatter.includesApproximationPhrase=trueformatter.string(from: loggedFlyingTime) // About 9 days
Chapter 5 extends what we learned about units in the previous chapterto transform Xcode Playgrounds into an interactive physical calculator.
lettakeoffWeight=( emptyPlaneWeight+ payloadWeight+ fuelWeight+ pilotWeight).converted(to:.pounds)letcanTakeOff= takeoffWeight< maximumTakeoffWeight // ???
MIT
Flight School is a book series for advanced Swift developersthat explores essential topics in iOS and macOS developmentthrough concise, focused guides.
If you'd like to get in touch,feel free tomessage us on Twitteror email us atinfo@flight.school.
About
Xcode Playground Sample Code for the Flight School Guide to Swift Numbers
Topics
Resources
License
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.