In this unit, we will delve into more advanced collection types in Swift, including tuples and optionals. We will also explore nested collections and higher-order functions.
Tuples group multiple values into a single compound value. The values within a tuple can be of any type and do not have to be of the same type as each other. Here's how you can define a tuple:
let http404Error = (404, "Not Found")
You can decompose a tuple’s contents into separate constants or variables, which you then access as you would any other constant or variable:
let (statusCode, statusMessage) = http404Error print("The status code is \(statusCode)") print("The status message is \(statusMessage)")
Optionals are used in Swift to handle the absence of a value. They are especially useful in collections when you're not sure if a certain key or index exists. Here's an example of using optionals with dictionaries:
var scores = ["Richard": 500, "Luke": 400, "Cheryl": 800] let score = scores["Michael"] // The "Michael" key does not exist, so score is an optional
Swift allows you to nest collections, such as having an array of arrays or an array of dictionaries. This can be useful when you want to group related data together. Here's an example of a nested array:
let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
And here's an example of an array of dictionaries:
let contacts = [ ["name": "Richard", "phone": "123-456"], ["name": "Luke", "phone": "789-012"], ["name": "Cheryl", "phone": "345-678"] ]
Swift provides several higher-order functions that you can use with collections, including map
, filter
, and reduce
.
map
applies a function to all items in a collection and returns the results in an array. For example:let numbers = [1, 2, 3, 4, 5] let squared = numbers.map { $0 * $0 } print(squared) // Prints "[1, 4, 9, 16, 25]"
filter
returns an array containing only the items that satisfy a certain condition. For example:let evenNumbers = numbers.filter { $0 % 2 == 0 } print(evenNumbers) // Prints "[2, 4]"
reduce
combines all items in a collection to create a single new value. For example:let sum = numbers.reduce(0, +) print(sum) // Prints "15"
By the end of this unit, you should have a solid understanding of how to work with advanced collection types in Swift.