100 Days of Swift - Day 5

davjvo

Davmi Jose Valdez Ogando

Posted on April 12, 2022

100 Days of Swift - Day 5

Continuation of Hacking With Swift 100 Days of Swift

Day 5 - Functions

Functions are a little bit special for swift, first of all return keyword is not required, function keyword gets boiled down to func, and return statements are specified with -> DataType; kind of bonkers if you ask me but hey, gotta get use to it.

In the other hand here we get an interesting concept, "parameter labels", these allow for a function to have an internal and external name for a passed parameter, ex:

func greet(to name: String) -> String { "Hello! \(name)" }; greet(to: "Davmi");

To get rid of the required parameter name when calling a function we can use the discard operator, the same way print() does not require the parameter to be set print(nameOfParameter: "") we can change our greet function like this:

func greet(_ name: String) -> String { "Hello! \(name)" };

And then the function can be called like: greet("Davmi");

Variadic functions are totally different, while on c# with have the params keyworks, on swift we use ... after the param type, so a variadic function would be

func variadicFunc(numbers: Int...)

In swift all parameters are immutable, in order to pass by reference (modify the value of the parameter), you need to add the ampersand symbol &.

💖 💪 🙅 🚩
davjvo
Davmi Jose Valdez Ogando

Posted on April 12, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

What was your win this week?
weeklyretro What was your win this week?

November 29, 2024

Where GitOps Meets ClickOps
devops Where GitOps Meets ClickOps

November 29, 2024

How to Use KitOps with MLflow
beginners How to Use KitOps with MLflow

November 29, 2024