Creating functions in Swift
In this post, I’ll show you how to create simple functions in Swift along with a little more complex functions that take parameters and can return a value.
An easy way to get some practice would be to open Playground and follow along.
Let’s start with a simple function:
This function is pretty straight forward.
As you can see, we can define a function by writing func than a open and close parentheses followed by open and close braces.
print() simply shows Hello World! in the console
We can call this function by writing the following:
By calling this function we should see Hello World! in the console.
Adding parameters
Now let’s get a bit more complex by creating a function that can take parameters and then will print them out.
In this example we have added name: String within the open & close parentheses.
This tells the function that we are going to pass a name every time we call our function.
We then use print(name) within the braces just like before.
When we call someFunc, we have to pass a name like so:
Make sure you pass a string, otherwise you’ll receive an error.
You may be thinking why do this?
Think about a situation where you need to use the same function 10 places in your application.
Having to write the same function 10 or so times is redundant besides when you need to change the function, do you really want to change the function 10 times? Possibly in 10 different places, in 10 different files?
Returning a value
Now we will use that same function that returned name to return the character count of name as a Int.
Here’s how our function will now look:
With our new function we have added -> Int after close parentheses.
By doing this, your basically telling the function that you promise to return a integer and only an integer.
Let’s call our function just like last time:
Now you will see on the right panel of Playground the returned value.
In the case of the function above, the return value is 11.
Keep in mind that using characters.count also counts spaces.
We can easily print this out in the console by wrapping our call of our function with print().