© Yanis Zafirópulos 2019
Yanis ZafirópulosSwift 4 Recipeshttps://doi.org/10.1007/978-1-4842-4182-0_10

10. Numbers and Dates

Yanis Zafirópulos1 
(1)
Granada, Spain
 

Numbers or numeric values, and dates, are one of the most common things a programmer has to deal with daily.

In this chapter, we’ll explore different ways that we can handle numbers in Swift, convert to and from different units, or make use of all of Swift’s mathematical capabilities and also see how we can make our life easier when working with date objects.

10.1 Calculate average of elements in array

Problem

I want to calculate the average of all elements in a given number array.

Solution

First, we initialize our example array.
let numbers = [1, 2, 3, 4, 5, 6]

Then, we calculate the average.

Note

To get the “real” average, we must make sure both parts – the average and the count – are Double and not integers.

let average = Double(numbers.reduce(0, +)) / Double(numbers.count)
Let’s see the result...
print("The average of our array is: (average)")

How It Works

If we want to calculate the average of the elements in a given array, we can use the Array’s reduce method and count property .
The average of our array is: 3.5

10.2 Calculate median of elements in array

Problem

I want to calculate the median of all the elements in a given number array.

Solution

Let’s initialize our example array.
let numbers = [5, 1, 3, 2, 4, 6]
First, we’ll sort our array, from smallest to largest.
let sorted = numbers.sorted()
Then, we’ll take the “middle” value – if there is one (if there is an odd number of elements in our array). Otherwise, we take the average of the two middle values.
let median = sorted.count % 2 == 1 ? Double(sorted[sorted.count/2])
                                                 : Double(sorted[sorted.count/2-1] + sorted[sorted.count/2]) / 2.0
Let’s see the result...
print("The median of our array is: (median)")

How It Works

If we want to calculate the median of the elements in a given array, we can use the Array’s sorted method .
The median of our array is: 3.5

10.3 Calculate product of elements in array

Problem

I want to calculate the product of all the elements in a given number array.

Solution

First, we initialize our example array.
let numbers = [2, 3, 4, 5]
Then, we calculate the product.
let product = numbers.reduce(1, *)
Let’s see the result...
print("The product of our array's elements is: (product)")

How It Works

If we want to calculate the product of all elements in a given array, we can use the Array’s reduce method .
The product of our array's elements is: 120

10.4 Calculate sum of elements in array

Problem

I want to calculate the sum of all the elements in a given number array.

Solution

First, we initialize our example array.
let numbers = [1, 2, 3, 4, 5, 6]
Then, we calculate the sum.
let sum = numbers.reduce(0, +)
Let’s see the result...
print("The sum of our array's elements is: (sum)")

How It Works

If we want to calculate the sum of all elements in a given array, we can use the Array’s reduce method .
The sum of our array's elements is: 21

10.5 Calculate the base-2 logarithm of a number

Problem

I want to calculate the base-2 logarithm of a given number.

Solution

import Foundation
First, we set our number.
let num = 16.0
And calculate its logarithm.
let result = _log2(num)
Let’s see the result...
print("Result: (result)")

How It Works

In order to calculate the base-2 logarithm of a number, we may use the _log2 function .
Result: 4.0

10.6 Calculate the cosine of an angle

Problem

I want to calculate the cosine of a given angle.

Solution

import Foundation
First, we set our (180-degree) angle and convert it to radians.
let angle = 180.0 * Double.pi / 180
And calculate its cosine.
let cosine = cos(angle)
Let’s see the result...
print("Result: (cosine)")

How It Works

In order to calculate the cosine of an angle, we may use the cos function.
Result: -1.0

10.7 Calculate the exponential of a number

Problem

I want to calculate the exponential of a given number.

Solution

import Foundation
First, we set our number.
let num = 3.0
And calculate its exponential.
let result = exp(num)
Let’s see the result...
print("Result: (result)")

How It Works

In order to calculate the exponential of a number, that is: the power e ^ x, we may use the exp function .
Result: 20.0855369231877

10.8 Calculate the inverse cosine of a number

Problem

I want to calculate the inverse cosine of a given number.

Solution

import Foundation
First, we set our number.
let num = -1.0
And calculate its inverse cosine.
let inv = acos(num)
Lastly, we may also convert it to degrees.
let angle = inv * 180 / Double.pi
Let’s see the result...
print("Result: (angle)")

How It Works

In order to calculate the inverse cosine of a number, we may use the acos function .
Result: 180.0

10.9 Calculate the inverse sine of a number

Problem

I want to calculate the inverse sine of a given number.

Solution

import Foundation
First, we set our number.
let num = 1.0
And calculate its inverse sine.
let inv = asin(num)
Lastly, we may also convert it to degrees.
let angle = inv * 180 / Double.pi
Let’s see the result...
print("Result: (angle)")

How It Works

In order to calculate the inverse sine of a number, we may use the asin function .
Result: 90.0

10.10 Calculate the inverse tangent of a number

Problem

I want to calculate the inverse tangent of a given number.

Solution

import Foundation
First, we set our number.
let num = 1.0
And calculate its inverse tangent.
let inv = atan(num)
Lastly, we may also convert it to degrees.
let angle = inv * 180 / Double.pi
Let’s see the result...
print("Result: (angle)")

How It Works

In order to calculate the inverse tangent of a number, we may use the atan function .
Result: 45.0

10.11 Calculate the logarithm of a number

Problem

I want to calculate the logarithm of a given number.

Solution

import Foundation
First, we set our number.
let num = 5.0
And calculate its logarithm.
let result = _log(num)
Let’s see the result...
print("Result: (result)")

How It Works

In order to calculate the (natural) logarithm of a number, we may use the _log function .
Result: 1.6094379124341

10.12 Calculate the nth factorial

Problem

I want to calculate the factorial of a given number.

Solution

Let’s calculate the 5th factorial (5!) – basically, we take the numbers 1,2,3,4,5 and find their product.

Careful: trying that with a larger number will quickly lead to an overflow!
let factorial = (1...5).reduce(1, *)
Let’s see the result...
print("5! = (factorial)")

How It Works

The Nth factorial is basically the product of numbers from 1 up to N. That’s why we can use the array’s reduce method along with the appropriate range.
5! = 120

10.13 Calculate the nth root of a number

Problem

I want to calculate a specific root of a given number.

Solution

import Foundation
First, we set our number.
let num = 16.0
And calculate its 4th root.
let root = pow(num, 1/4)
Let’s see the result...
print("The 4th root of (num) is: (root)")

How It Works

In order to calculate the Nth root of a number, we may use the pow function.
The 4th root of 16.0 is: 2.0

10.14 Calculate the power of a number

Problem

I want to calculate the power of a given number.

Solution

import Foundation
First, we set our number.
let num = 5.0
And calculate the power (num ^ 3).
let power = pow(num, 3)
Let’s see the result...
print("(num) ^ 3 = (power)")

How It Works

In order to calculate the power of a number, we may use the pow function .
5.0 ^ 3 = 125.0

10.15 Calculate the sine of an angle

Problem

I want to calculate the sine of a given angle.

Solution

import Foundation
First, we set our (90-degree) angle and convert it to radians.
let angle = 90.0 * Double.pi / 180
And calculate its sine.
let sine = sin(angle)
Let’s see the result...
print("Result: (sine)")

How It Works

In order to calculate the sine of an angle, we may use the sin function .
Result: 1.0

10.16 Calculate the square of a number

Problem

I want to calculate the square of a given number.

Solution

import Foundation
First, we set our number.
let num = 3.0
And calculate its square.
let squared = pow(num, 2)
Let’s see the result...
print("(num) ^ 2 = (squared)")

How It Works

In order to calculate the square of a number, we may use the pow function.
3.0 ^ 2 = 9.0

10.17 Calculate the square root of a number

Problem

I want to calculate the square root of a given number.

Solution

import Foundation
First, we set our number.
let num = 16.0
And calculate its square root.
let root = sqrt(num)
Let’s see the result...
print("The square root of (num) is: (root)")

How It Works

In order to calculate the square root of a number, we may use the sqrt function.
The square root of 16.0 is: 4.0

10.18 Calculate the tangent of an angle

Problem

I want to calculate the tangent of a given angle.

Solution

import Foundation
First, we set our (45-degree) angle and convert it to radians.
let angle = 45.0 * Double.pi / 180
And calculate its tangent.
let tangent = tan(angle)
Let’s see the result...
print("Result: (tangent)")

How It Works

In order to calculate the tangent of an angle, we may use the tan function.
Result: 1.0

10.19 Check if object is integer

Problem

I want to check if a given object is of type Int.

Solution

First, we initialize our example “object” - let’s make it a string.
var a : Any = "nope"
Now, let’s see...
if a is Int {
      print("Yes, it's an integer. Yay!")
} else {
      print("Oh, no, something went wrong. it's not an integer!")
}

How It Works

To check if an object is of type Int, we can use an X is Int statement .
Oh, no, something went wrong. it's not an integer!

10.20 Convert between angle units

Problem

I want to make a conversion between different angle units.

Solution

Available angle units: .arcMinutes, .arcSeconds, .degrees, .gradians, .radians, .revolutions
import Foundation

Let’s make sure we’re on OSX 10.12 or newer. Otherwise, this won’t work.

if #available(OSX 10.12, *) {
      // First, we set some example value, in degrees
      let angle = Measurement(value: 100, unit: UnitAngle.degrees)
      // Then we convert our angle to radians
      let converted = angle.converted(to: .radians)
      // And print it out
      print("(angle) = (converted)")
} else {
      print(":-(")
}

How It Works

In order to convert a given value between different angle units, that is: from degrees to radians, from gradians to revolutions, and so on, you may use the very handy Measurement class.
100.0 ° = 1.74532862792735 rad

10.21 Convert between area units

Problem

I want to make a conversion between different area units.

Solution

Available area units:
.acres, .ares, .hectares, .squareCentimeters, .squareFeet, .squareInches, .squareKilometers, .squareMegameters, .squareMeters, .squareMicrometers, .squareMiles, .squareMillimeters, .squareNanometers, .squareYards
import Foundation
Let’s make sure we’re on OSX 10.12 or newer. Otherwise, this won’t work.
if #available(OSX 10.12, *) {
      // First, we set some example value, in square meters
      let area = Measurement(value: 1000, unit: UnitArea.squareMeters)
      // Then we convert our area to acres
      let converted = area.converted(to: .acres)
      // And print it out
      print("(area) = (converted)")
} else {
      print(":-(")
}

How It Works

In order to convert a given value between different area units, that is: from square meters to hectares, from acres to square yards, and so on, you may use the very handy Measurement class.
1000.0 m2 = 0.247105163015276 ac

10.22 Convert between length units

Problem

I want to make a conversion between different length units.

Solution

Available length units:
.astronomicalUnits, .centimeters, .decameters, .decimeters, .fathoms, .feet, .furlongs, .hectometers, .inches, .kilometers, .lightyears, .megameters, .meters, .micrometers, .miles, .millimeters, .nanometers, .nauticalMiles, .parsecs, .picometers, .scandinavianMiles, .yards
import Foundation
Let’s make sure we’re on OSX 10.12 or newer. Otherwise, this won’t work.
if #available(OSX 10.12, *) {
      // First, we set some example value, in meters
      let length = Measurement(value: 100, unit: UnitLength.meters)
      // Then we convert our length to feet
      let converted = length.converted(to: .feet)
      // And print it out
      print("(length) = (converted)")
} else {
      print(":-(")
}

How It Works

In order to convert a given value between different length units, that is: from meters to feet, from inches to yards, and so on, you may use the very handy Measurement class.
100.0 m = 328.083989501312 ft

10.23 Convert between volume units

Problem

I want to make a conversion between different volume units.

Solution

Available volume units:
.acreFeet, .bushels, .centiliters, .cubicCentimeters, .cubicDecimeters, .cubicFeet, .cubicInches, .cubicKilometers, .cubicMeters, .cubicMiles, .cubicMillimeters, .cubicYards, .cups, .deciliters, .fluidOunces, .gallons, .imperialFluidOunces, .imperialGallons, .imperialPints, .imperialQuarts, .imperialTablespoons, .imperialTeaspoons, .kiloliters, .liters, .megaliters, .metricCups, .milliliters, .pints, .quarts, .tablespoons, .teaspoons
import Foundation
Let’s make sure we’re on OSX 10.12 or newer. Otherwise, this won’t work.
if #available(OSX 10.12, *) {
      // First, we set some example value, in liters
      let volume = Measurement(value: 1, unit: UnitVolume.liters)
      // Then we convert our volume to tablespoons
      let converted = volume.converted(to: .tablespoons)
      // And print it out
      print("(volume) = (converted)")
} else {
      print(":-(")
}

How It Works

In order to convert a given value between different volume units, that is: from square cubic meters to bushels, or even liters to teaspoons, you may use the very handy Measurement class.
1.0 L = 67.6278843292666 tbsp

10.24 Convert degrees to radians

Problem

I want to convert an angle, from degrees to radians.

Solution

import Foundation
Let’s set our test value.
let degrees = 21.0
Then, we convert it to radians.
let radians = degrees * Double.pi / 180.0
And print out the result...
print("(degrees) degrees = (radians) radians")

How It Works

In order to convert degrees to radians, we can use the known formula: r = d * pi / 180
21.0 degrees = 0.366519142918809 radians

10.25 Convert double to integer

Problem

I want to convert a given double number to Int.

Solution

Let’s create our test number.
let d : Double = 18.96
Let’s convert it to an Int.
let i = Int(d)
And print it out...
print("Result: (i)")

How It Works

In order to convert a double to Int, we can easily use the Int initializer.
Result: 18

10.26 Convert double to string

Problem

I want to convert a given double number to its string representation.

Solution

Let’s create our test double.
let a : Double = 6.2
Let’s convert it to a string.
let str = String(a)
And print it out...
print("Result: (str)")

How It Works

In order to convert a double to string, we can easily use the String initializer.
Result: 6.2

10.27 Convert float to CGFloat

Problem

I want to convert a Float number to a CGFloat.

Solution

import Foundation
Let’s create our test number.
let f : Float = 18.96
Let’s convert it to a CGFloat.
let cf = CGFloat(f)
And print it out...
print("Result: (cf)")

How It Works

In order to convert a Float to CGFloat, we can easily use the CGFloat initializer.
Result: 18.9599990844727

10.28 Convert float to integer

Problem

I want to convert a float number to an Int.

Solution

Let’s create our test number.
let f : Float = 18.96
Let’s convert it to an Int.
let i = Int(f)
And print it out...
print("Result: (i)")

How It Works

In order to convert a float to int, we can easily use the Int initializer.
Result: 18

10.29 Convert float to string

Problem

I want to convert a float number to its string representation.

Solution

Let’s create our test floating-point number.
let a : Float = 4.3
Let’s convert it to a string.
let str = String(a)
And print it out...
print("Result: (str)")

How It Works

In order to convert a float to string, we can easily use the String initializer.
Result: 4.3

10.30 Convert integer to double

Problem

I want to convert an int number to double.

Solution

Let’s create our test number.
let i = 11
Let’s convert it to a Double.
let d = Double(i)
And print it out...
print("Result: (d)")

How It Works

In order to convert an int to double, we can easily use the double initializer.
Result: 11.0

10.31 Convert integer to float

Problem

I want to convert an int number to float.

Solution

Let’s create our test number.
let i = 16
Let’s convert it to a float.
let f = Float(i)
And print it out...
print("Result: (f)")

How It Works

In order to convert an int to float, we can easily use the Float initializer.
Result: 16.0

10.32 Convert integer to string

Problem

I want to convert an int number to its string representation.

Solution

Let’s create our test integer.
let a : Int = 6
Let’s convert it to a string.
let str = String(a)
And print it out...
print("Result: (str)")

How It Works

In order to convert an int to string, we can easily use the String initializer.
Result: 6

10.33 Convert radians to degrees

Problem

I want to convert an angle, from radians to degrees.

Solution

import Foundation
Let’s set our test value.
let radians = 0.3
Then, we convert it to degrees.
let degrees = radians * 180 / Double.pi
And print out the result...
print("(radians) radians = (degrees) degrees")

How It Works

In order to convert radians to degrees, we can use the known formula: d = r * 180 / pi
0.3 radians = 17.188733853924695 degrees

10.34 Generate a random number within range

Problem

I want to generate a random number within a specific range.

Solution

import Foundation
Let’s generate our random number. We want a random number between 2 and 10 (not including 10).
let rand = Int.random(in: 2..10)
And... print it out.
print("Our random number is: (rand)")

How It Works

In order to generate a random number, within a specific range, we’ll be using the Int.random(in:) function .
Our random number is: 7

10.35 Generate a random number

Problem

I want to generate any random number.

Solution

import Foundation
Let’s generate our random number.
let rand = Int.random(in:0..1000)
And... print it out.
print("Our random number is: (rand)")

How It Works

In order to generate a random number, we’ll be using the Int.random(in:) function .
Our random number is: 18

10.36 Get absolute value of number

Problem

I want to get the absolute value of a given number.

Solution

First, let’s take a test number.
let x = -10
Then, we get its absolute value.
let absolute = abs(x)
And print it out...
print("The absolute value of (x) is: (absolute)")

How It Works

In order to get the absolute value of a number, we can use the abs function.
The absolute value of -10 is: 10

10.37 Get maximum of two values

Problem

I want to get the maximum of two given values.

Solution

First, let’s take some test numbers.
let a = 5
let b = -2
Then, we calculate their maximum.
let maximum = max(a, b)
And print it out...
print("The maximum is: (maximum)")

How It Works

In order to get the maximum of two given values, we can use the max function.
The maximum is: 5

10.38 Get minimum of two values

Problem

I want to get the minimum of two given values.

Solution

First, let’s take some test numbers.
let a = -10
let b = 6
Then, we calculate their minimum.
let minimum = min(a, b)
And print it out...
print("The minimum is: (minimum)")

How It Works

In order to get the maximum of two given values, we can use the min function.
The minimum is: -10

10.39 Round decimal down to whole number

Problem

I want to round a given decimal value down to a whole number.

Solution

import Foundation
First, we set our test numbers.
let a = 1.21
let b = 1.42
let c = 1.73
What about rounding them?
let roundA = floor(a)
let roundB = floor(b)
let roundC = floor(c)
Let’s print the results...
print("(a) => (roundA)")
print("(b) => (roundB)")
print("(c) => (roundC)")

How It Works

In order to round a decimal number down to a whole number, we may use the floor function.
1.21 => 1.0
1.42 => 1.0
1.73 => 1.0

10.40 Round decimal to nearest whole number

Problem

I want to round a given decimal value to the nearest whole number.

Solution

import Foundation
First, we set our test numbers.
let a = 1.21
let b = 1.42
let c = 1.73
What about rounding them?
let roundA = round(a)
let roundB = round(b)
let roundC = round(c)
Let’s print the results...
print("(a) => (roundA)")
print("(b) => (roundB)")
print("(c) => (roundC)")

How It Works

In order to round a decimal number to the nearest whole number, we may use the round function.
1.21 => 1.0
1.42 => 1.0
1.73 => 2.0

10.41 Round decimal up to whole number

Problem

I want to round a given decimal value up to a whole number.

Solution

import Foundation
First, we set our test numbers.
let a = 1.21
let b = 1.42
let c = 1.73
What about rounding them?
let roundA = ceil(a)
let roundB = ceil(b)
let roundC = ceil(c)
Let’s print the results...
print("(a) => (roundA)")
print("(b) => (roundB)")
print("(c) => (roundC)")

How It Works

In order to round a decimal number up to a whole number, we may use the ceil function.
1.21 => 2.0
1.42 => 2.0
1.73 => 2.0

10.42 Calculate date after adding to date

Problem

I want to calculate the resulting date after adding an interval to a given date.

Solution

import Foundation
First, we keep a reference to our current date – that is: now.
let now = Date()
Let’s say we want to get the date, 10 days from now. That is: We’ll add 10 days to our current date.
let futureDate = Calendar.current.date(byAdding: .day, value: 10, to: now)
Let’s print that future date...
print("10 days from now: (futureDate!)")

How It Works

In order to calculate a date, based on a given date object, after some time has passed, we can use the current Calendar’s, date(byAdding:value:to:) method .
10 days from now: 2017-03-21 11:38:47 +0000

10.43 Check if date is in the future

Problem

I want to check if a given date is in the future.

Solution

import Foundation
First, we set our given date to some test date.
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let date = formatter.date(from: "1986-10-27")
Then we keep a reference to our current date – that is: now.
let now = Date()

Time to compare them.

Note

date is an optional. But in this case, it’s rather safe to force-unwrap it.

if date! > now {
      print("Yes, it's in the future.")
} else {
      print("No, it's not in the future.")
}

How It Works

In order to check if a specific Date object is in the future, we can simply compare it with our current date.
No, it's not in the future.

10.44 Check if date is in the past

Problem

I want to check if a given date is in the past.

Solution

import Foundation
First, we set our given date to some test date.
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let date = formatter.date(from: "1986-10-27")
Then we keep a reference to our current date – that is: now.
let now = Date()

Time to compare them.

Note

a is an optional. But in this case, it’s rather safe to force-unwrap it.

if date! < now {
      print("Yes, it's in the past.")
} else {
      print("No, it's not in the past.")
}

How It Works

In order to check if a specific Date object is in the past, we can simply compare it with our current date.
Yes, it's in the past.

10.45 Check if date is today

Problem

I want to check if a given date is today.

Solution

import Foundation
First, we set our given date to some test date.
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let a = formatter.date(from: "1986-10-27")
Then we keep a reference to our current date – that is: now.
let b = Date()
Then, we extract the desired components from each date, namely: year, month, and day.
let dateToCheck = Calendar.current.dateComponents([.year, .month, .day], from: a!)
let currentDate = Calendar.current.dateComponents([.year, .month, .day], from: b)
Time to check if they coincide.
if dateToCheck.year  == currentDate.year &&
   dateToCheck.month == currentDate.month &&
   dateToCheck.day   == currentDate.day {
      print("Yep, it's today.")
} else {
      print("Well, this date we gave me... it's not today!")
}

How It Works

In order to check if a specific Date object is today, we can use the DateComponents class to retrieve the different components of the given date, and then compare them with our current date.
Well, this date we gave me... it's not today!

10.46 Check if two dates are equal

Problem

I want to check if two different dates are equal.

Solution

import Foundation
First, we initialize our dates.
let a = Date()

Note

This is not the same as above. A few milliseconds have passed, so it’s a 100% distinct date ;-)

let b = Date()
Now, let’s see...
if a == b {
      print("Yes, they are the same.")
} else {
      print("Nope, they are not equal - wait, what?!")
}

How It Works

To compare two dates and check if they are equal, we can use the == comparison operator. (The result of this specific example may, at times, differ in the given the different CPU time spent creating both date objects).
Nope, they are not equal - wait, what?!

10.47 Compare two dates

Problem

I want to compare two different dates.

Solution

import Foundation
First, we initialize our dates.
let a = Date()

Note

This is not the same as above.

A few milliseconds have passed, so it’s a 100% distinct date ;-)

let b = Date()

Now, let’s see...

if a < b {       print("Date A comes before Date B") }else {       print("Date B comes before Date A") }

How It Works

To compare two dates - that is: which one *would* come first, we can use the < and > comparison operators.
Date A comes before Date B

10.48 Create date from current date

Problem

I want to create a date object from the current date.

Solution

import Foundation
Let’s create our date.
let now = Date()
And print it out – yes, it was that simple!
print("Current date: (now)")

How It Works

In order to create a new date object for the current date and time we can use date’s initializer.
Current date: 2017-03-11 11:38:49 +0000

10.49 Create date from given date

Problem

I want to create a date object from a given date.

Solution

import Foundation
First, we set our desired year/month/day.
var date = DateComponents()
date.year = 2016
date.month = 10
date.day = 27
Then, we create our NSDate object.
let dateObj = Calendar.current.date(from: date)

And print it out.

Note

It’s optional, but there is no harm force-unwrapping it in this particular case.

print("Given date: (dateObj!)")

How It Works

In order to create a new Date object, for a given year/month/day, we can use the DateComponents class, along with the current Calendar.
Given date: 2016-10-26 22:00:00 +0000

10.50 Create date from given string format

Problem

I want to create a Date object from a given string format.

Solution

import Foundation
First, we set a test date string.
let dateString = "2016-10-27"
Then, we initialize a DateFormatter and set a date format.
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
Lastly, we convert our date to a date object.
let date = formatter.date(from: dateString)

Let’s see what we’ve managed...

Note

It’s optional, but there is no harm in force-unwrapping it in this particular case.

print("Date: (date!)")

How It Works

In order to create a new date object, from a given formatted string, we can use the DateFormatter class.
Date: 2016-10-26 22:00:00 +0000

10.51 Find date in string

Problem

I want to find a date in a specific string.

Solution

import Foundation
Let’s set some example text.
let text = "This is a random date: 03/01/2017"
Let’s create our detector. We want the dates, so we’ll look for this: NSTextCheckingResult.CheckingType.date.rawValue.
let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.date.rawValue)
let results = detector.matches(in: text, options: [], range: NSRange(location: 0, length: text.count))
Loop through the dates we found.
for result in results {
      // And print them out
      print(result.date!)
}

How It Works

In order to find a date within some text, we may use the NSDataSelector class .
2017-03-01 11:00:00 +0000

10.52 Format string from date

Problem

I want to format a string from a given date.

Solution

import Foundation
First, we set our date – to... now.
let date = Date()
Then, we initialize a DateFormatter and set a date format.
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
Lastly, we convert our date to a date string.
let dateStr = formatter.string(from: date)
Let’s see what we’ve managed...
print("Date: (dateStr)")

How It Works

In order to get a string for a given date, we can use the DateFormatter class .
Date: 2017-03-11

10.53 Get components from date

Problem

I want to get the different components of a given date.

Solution

import Foundation
First, we set our desired date – to... now.
var date = Date()
Then, we extract the desired components, namely: year, month, and day.
let components = Calendar.current.dateComponents([.year, .month, .day], from: date)

Let’s see what we’ve got...

Note

All of the data is optional, but in this particular case, it’s rather safe to force-unwrap them.

print("Year: (components.year!)")
print("Month: (components.month!)")
print("Day: (components.day!)")

How It Works

In order to get a Date’s individual components, for example, day, month, year, we can use the DateComponents class .
Year: 2018
Month: 10
Day: 8

10.54 Get day from date

Problem

I want to get the day component of a given date.

Solution

import Foundation
First, we set our desired date – to... now.
var date = Date()
Then, we extract the desired component, that is: the day.
let day = Calendar.current.component(.day, from: date)
Let’s print it out...
print("Current day: (day)")

How It Works

In order to get the day from a Date object, we can use the current Calendar’s component(_:from:) method .
Current day: 11

10.55 Get days difference between dates

Problem

I want to get the difference, in days, between two different dates.

Solution

import Foundation
First, we create our Date objects.
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let a = formatter.date(from: "1986-10-27")
let b = formatter.date(from: "2016-12-30")

We want the difference in days. So we set that to: .day

Note

Other possible values: .year, .month, .day, .hour, .minute, .nanosecond

let unit : Calendar.Component = .day
Time to get their difference.
let start = Calendar.current.ordinality(of: unit, in: .era, for: a!)
let end = Calendar.current.ordinality(of: unit, in: .era, for: b!)
They are both optional, but in this case it’s pretty safe to force-unwrap them.
let diff = end! - start!
And let’s print the result...
print("Difference: (diff) days")

How It Works

In order to calculate the difference in seconds between two different Date objects, we may use the current Calendar and its ordinality(of:in:for:) method .
Difference: 11022 days

10.56 Get month from date

Problem

I want to get the month component of a given date.

Solution

import Foundation
First, we set our desired date – to... now.
var date = Date()
Then, we extract the desired component, that is: the month.
let month = Calendar.current.component(.month, from: date)
Let’s print it out...
print("Current month: (month)")

How It Works

In order to get the month from a date object, we can use the current Calendar’s component(_:from:) method .
Current month: 3

10.57 Get month name from date

Problem

I want to get the month name component of a given date.

Solution

import Foundation
First, we set our desired date – to... now.
var date = Date()
Then, we extract the desired component, that is: the month.
let month = Calendar.current.component(.month, from: date)
And match it to the appropriate name.
let months = ["January", "February", "March", "April", "May", "June",
                    "July", "August", "September", "October", "November", "December"]
let monthName = months[month-1]
Let’s print it out...
print("Current month: (monthName)")

How It Works

In order to get the month name from a Date object, we can use the current Calendar’s component(_:from:) method .
Current month: March

10.58 Get seconds difference between times

Problem

I want to get the difference, in seconds, between two different times.

Solution

import Foundation
First, we create our date objects with a delay of 2 seconds in between.
let a = Date()
sleep(2)
let b = Date()

We want the difference in seconds. So we set that to: .second.

Note

Other possible values: .year, .month, .day, .hour, .minute, .nanosecond

let unit : Calendar.Component = .second
Time to get their difference
let start = Calendar.current.ordinality(of: unit, in: .year, for: a)
let end = Calendar.current.ordinality(of: unit, in: .year, for: b)
They are both optional, but in this case it’s pretty safe to force-unwrap them.
let diff = end! - start!
And let’s print the result...
print("Difference: (diff) seconds")

How It Works

In order to calculate the difference in seconds between two different Date objects, we may use the current Calendar and its ordinality(of:in:for:) method .
Difference: 2 seconds

10.59 Get Unix timestamp for current date

Problem

I want to get the Unix timestamp for the current date.

Solution

import Foundation
Let’s create our date.
let now = Date()
Get the timestamp.
let timestamp = now.timeIntervalSince1970
And print it out – yes, it was that simple.
print("Current Unix timestamp: (timestamp)")

How It Works

In order to get the Unix timestamp for the current date, we have to create a new Date object, for current date and time, and its timeIntervalSince1970 property.
Current Unix timestamp: 1489232335.80579

10.60 Get year from date

Problem

I want to get the year component of a given date.

Solution

import Foundation
First, we set our desired date – to... now.
var date = Date()
Then, we extract the desired component, that is: the year.
let year = Calendar.current.component(.year, from: date)
Let’s print it out...
print("Current year: (year)")

How It Works

In order to get the year from a Date object, we can use the current Calendar’s component(_:from:) method .
Current year: 2018

10.61 Summary

In this chapter, we learned how we can make the most out of numbers and dates.

In the next one, we’ll be looking into Errors and Exceptions: that is, how we can create our own custom types and be able to predict and prevent different – unpleasant – scenarios during our app’s execution.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.127.37