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.
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
First, we set our number.
And calculate its logarithm.
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
.
10.6 Calculate the cosine of an angle
Problem
I want to calculate the cosine of a given angle.
Solution
First, we set our (180-degree) angle and convert it to radians.
let angle = 180.0 * Double.pi / 180
And calculate its cosine.
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.
10.7 Calculate the exponential of a number
Problem
I want to calculate the exponential of a given number.
Solution
First, we set our number.
And calculate its exponential.
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
.
10.8 Calculate the inverse cosine of a number
Problem
I want to calculate the inverse cosine of a given number.
Solution
First, we set our number.
And calculate its inverse cosine.
Lastly, we may also convert it to degrees.
let angle = inv * 180 / Double.pi
How It Works
In order to calculate the inverse cosine of a
number, we may use the
acos function
.
10.9 Calculate the inverse sine of a number
Problem
I want to calculate the inverse sine of a given number.
Solution
First, we set our number.
And calculate its inverse sine.
Lastly, we may also convert it to degrees.
let angle = inv * 180 / Double.pi
How It Works
In order to calculate the inverse sine of a
number, we may use the
asin function
.
10.10 Calculate the inverse tangent of a number
Problem
I want to calculate the inverse tangent of a given number.
Solution
First, we set our number.
And calculate its inverse tangent.
Lastly, we may also convert it to degrees.
let angle = inv * 180 / Double.pi
How It Works
In order to calculate the inverse tangent of a
number, we may use the
atan function
.
10.11 Calculate the logarithm of a number
Problem
I want to calculate the logarithm of a given number.
Solution
First, we set our number.
And calculate its logarithm.
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
.
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.
10.13 Calculate the nth root of a number
Problem
I want to calculate a specific root of a given number.
Solution
First, we set our number.
And calculate its 4th root.
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
First, we set our number.
And calculate the power (
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
.
10.15 Calculate the sine of an angle
Problem
I want to calculate the sine of a given angle.
Solution
First, we set our (90-degree) angle and convert it to radians.
let angle = 90.0 * Double.pi / 180
How It Works
In order to calculate the
sine of an angle, we may use the
sin function
.
10.16 Calculate the square of a number
Problem
I want to calculate the square of a given number.
Solution
First, we set our number.
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.
10.17 Calculate the square root of a number
Problem
I want to calculate the square root of a given number.
Solution
First, we set our number.
And calculate its square root.
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
First, we set our (45-degree) angle and convert it to radians.
let angle = 45.0 * Double.pi / 180
And calculate its tangent.
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.
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.
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, .revolutionsLet’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)
print("(angle) = (converted)")
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
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)
print("(area) = (converted)")
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
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)
print("(length) = (converted)")
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
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)
print("(volume) = (converted)")
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
Let’s set our test value.
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 / 18021.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’s convert it to an
Int.
How It Works
In order to convert a double to
Int, we can easily use the
Int initializer.
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’s convert it to a string.
How It Works
In order to convert a
double to string, we can easily use the
String initializer.
10.27 Convert float to CGFloat
Problem
I want to convert a Float number to a CGFloat.
Solution
Let’s create our test number.
Let’s convert it to a
CGFloat.
How It Works
In order to convert a
Float to CGFloat, we can easily use the
CGFloat initializer.
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’s convert it to an
Int.
How It Works
In order to convert a float to
int, we can easily use the
Int initializer.
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’s convert it to a string.
How It Works
In order to convert a
float to string, we can easily use the
String initializer.
10.30 Convert integer to double
Problem
I want to convert an int number to double.
Solution
Let’s create our test number.
Let’s convert it to a
Double.
How It Works
In order to convert an int to
double, we can easily use the
double initializer.
10.31 Convert integer to float
Problem
I want to convert an int number to float.
Solution
Let’s create our test number.
Let’s convert it to a
float.
How It Works
In order to convert an int to
float, we can easily use the
Float initializer.
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’s convert it to a string.
How It Works
In order to convert an int to
string, we can easily use the
String initializer.
10.33 Convert radians to degrees
Problem
I want to convert an angle, from radians to degrees.
Solution
Let’s set our test value.
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 / pi0.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
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
.
10.35 Generate a random number
Problem
I want to generate any random number.
Solution
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
.
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.
Then, we get its absolute value.
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.
Then, we calculate their maximum.
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.
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.
Then, we calculate their minimum.
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.
10.39 Round decimal down to whole number
Problem
I want to round a given decimal value down to a whole number.
Solution
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
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
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
First, we keep a reference to our current date – that is: now.
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
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.
Time to compare them.
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
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.
Time to compare them.
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.
10.45 Check if date is today
Problem
I want to check if a given date is today.
Solution
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.
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
First, we initialize our dates.
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
First, we initialize our dates.
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
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
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.
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
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...
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
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.
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
First, we set our date – to... now.
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...
How It Works
In order to get a string for a given
date, we can use the
DateFormatter class
.
10.53 Get components from date
Problem
I want to get the different components of a given date.
Solution
First, we set our desired date – to... now.
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...
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
First, we set our desired date – to... now.
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
.
10.55 Get days difference between dates
Problem
I want to get the difference, in days, between two different dates.
Solution
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
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.
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
.
10.56 Get month from date
Problem
I want to get the month component of a given date.
Solution
First, we set our desired date – to... now.
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
.
10.57 Get month name from date
Problem
I want to get the month name component of a given date.
Solution
First, we set our desired date – to... now.
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
.
10.58 Get seconds difference between times
Problem
I want to get the difference, in seconds, between two different times.
Solution
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.
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.
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
.
10.59 Get Unix timestamp for current date
Problem
I want to get the Unix timestamp for the current date.
Solution
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
First, we set our desired date – to... now.
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
.
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.