DEV Community

loading...
Cover image for Recap:  My First Week of Learning Swift...Part 2

Recap: My First Week of Learning Swift...Part 2

KeeyboardKeda
Hey ! I'm here to track my progress/ journey on becoming an iOS developer.
・2 min read

Days 5 & 6:

Functions and Parameters

Functions allow us to re-use code in different places. If the code in the function is changed, it will be updated everywhere that function is being used. It is common to use functions to break up large code to make it easier to follow. All parameters are constants which mean they cannot be changed. To change them the keyword inout must be used and it will change inside and outside the function. Parameters in functions are given a name and a type. For example, name: string. They can be given an external and internal label but if we prefer not to use an external label it can be replaced with an underscore. We can give a parameter a default value. For example,...new: bool = true. Variadic functions accept any number of parameters of the same type. Any parameter can become variadic by adding (...) after its type. We can throw functions by using enums to describe the errors we can throw.Its good to know that Swift wont let us run an error-throwing function by accident.

Closures

There is so much that goes into closures so I'm going to be brief. Functions can be used like types. We can create a function and assign it to a variable, call the function using the variable and even pass it into another function as a parameter. This process is called closures. Closures accept parameters and can be used as a parameter. They can also return values. If a closure is the last value in a function we can use a special syntax called trailing closure syntax. This passes the closure after the function inside the braces.
If we want to use closures as parameters when they accept parameters just add the parameter inside the parentheses of () -> Void. Void can be replaced with any type of data to force the closure to return a value.

If you read part 1 and part 2, thank you and I hope it made sense to you. If not, that ok too! I wanted to do this to deepen what I have learned so far.

Until tomorrow !

Discussion (0)