Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Oct 19, 2024. It is now read-only.

Xcode Playground Sample Code for the Flight School Guide to Swift Numbers

License

NotificationsYou must be signed in to change notification settings

Flight-School/Guide-to-Swift-Numbers-Sample-Code

Repository files navigation

Flight School Guide to Swift Codable Cover

Guide to Swift Numbers Sample Code

Build StatusLicenseSwift Version

This repository contains sample code used in theFlight School Guide to Swift Numbers.


Chapter 1

Chapter 1 is a conceptual deep-dive intohow numbers work on computers in generaland in Swift specifically.

Floating Point Approximates

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

Floating Point Environment

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

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.

Cardinal Numbers

letformatter=NumberFormatter()formatter.string(for:4) // 4formatter.numberStyle=.spellOutformatter.string(for:4) // four

Ordinal Numbers

letformatter=NumberFormatter()formatter.numberStyle=.ordinalformatter.string(for:1) // 1st

Decimal Numbers

letformatter=NumberFormatter()formatter.numberStyle=.decimalformatter.string(for:1234567.89)1,234,567.89

Significant Digits

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

Integer and Fraction Digits

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

Rounding Modes

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)}}

Scientific Notation

letformatter=NumberFormatter()formatter.numberStyle=.scientificformatter.string(for:12345.6789) // 1.23456789E4

Percentages

letformatter=NumberFormatter()formatter.numberStyle=.percentformatter.string(for:0.12) // 12%

Currencies

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)}}

Custom Formats

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

Chapter 3 shows the correct way to represent and work with money in code.

Money

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

Currency Converter

letEURtoUSD=CurrencyPair<EUR,USD>(rate:1.17) // as of June 1st, 2018leteuroAmount:Money<EUR>=123.45letdollarAmount=EURtoUSD.convert(euroAmount) // $144.44

Chapter 4

Chapter 4 covers Foundation's units and measurements APIs.

Natural Scale

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

Provided Units

letingotMass=Measurement<UnitMass>(value:400, unit:.ouncesTroy)letformatter=MeasurementFormatter()formatter.unitOptions=.providedUnitformatter.string(from: ingotMass) // 400 oz t

Configuring Precision

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

Temperature Formatting

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°

Units Interoperability

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

Chapter 5 extends what we learned about units in the previous chapterto transform Xcode Playgrounds into an interactive physical calculator.

Agricultural Flight Planner

lettakeoffWeight=(    emptyPlaneWeight+    payloadWeight+    fuelWeight+    pilotWeight).converted(to:.pounds)letcanTakeOff= takeoffWeight< maximumTakeoffWeight // ???

License

MIT

About Flight School

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

Stars

Watchers

Forks

Releases

No releases published

Sponsor this project

    Packages

    No packages published

    Languages


    [8]ページ先頭

    ©2009-2025 Movatter.jp