iOS Development — Week 3
3 min readSep 5, 2022
That was the end of week 3 — yes I am a bit late posting this… We continued learning Swift, this time it was all about functions, types, closures and advanced swift features.
Closures
- Think of them as “blocks of code that do something
- Differences between closures and functions:
Closures Feature Functions No Names? Yes No Argument labels? Yes No Default parameters? Yes Yes Write Inline? No { (a: Int, b: Int) -> Int in a * b }
Different syntax func multiply(a: Int, b: Int) -> Int { a * b }
We have also covered some useful higher order functions:
forEach
- Always runs on all elements, you can pass functions and chain with other methods. Notice that a for loop can usebreak
andcontinue
andwhere
clauses. These do not work withforEach
map
- Goes through all elements of a collection, operate on every single element, and return a new collection with the results.compactMap
- Only returns collection elements that are notnil
flatMap
- Lets us handle multidimensional arrays. It expects an array as inputfilter
- Filters out the elements that meet the required conditionsreduce
- Takes two arguments: an initial value and a closure