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

Get Swift 4 Recipes: Hundreds of Useful Hand-picked Code Snippets now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.