In this blog, I’ll explain 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 method to obtain some practice would be to open and follow beside.
Let’s begin with a simple function:
func someFunctionName () { print("Hello World!") }
This function is attractive straight forward.
As you can observe, we can describe a function by writing func than an open and close parentheses followed by open and close braces.
print() simply explains Hello World! In the console
We preserve call this function by writing the following:
someFunctionName()
By calling this function we must observe Hello World! in the console.
Including parameters
Now let’s obtain a bit more complex by creating a function that can take parameters and then will print them out.
In this example we have further name: String within the open & close parentheses.
This informs the function that we are going to pass a name all time we call our function.
func someFunc (name: String) { print(name) }
Then we use print(name) within the braces just like previous.
When we call someFunc, we have to go by a name like so:
someFunc(name: "fathima")
Ensure you pass a string, otherwise you’ll receive an error.
You might be thinking why do this?
Consider about a situation where you want to use the same function 10 places in your application.
Having to write the same function 10 or so times is unnecessary besides when you need to change the function, do you really want to change the function 10 times? perhaps in 10 different places, in 10 different files?
Returning a value
Now we will utilize that same function that returned name to return the character count of name as a Int.
Here’s how our function will now appear:
func someFunc (name: String) -> Int { return name.characters.count }
With our new function we have included -> Int after close parentheses.
By doing this, you’re essentially telling the function that you promise to return a integer and only an integer.
Let’s call our function just like last time:
someFunc(name: "Fathima")
Now you will observe on the right panel of Playground the returned value.
In the above case of the function, the return value is 11.
Remind that using characters.count also counts spaces.
We can simply print this out in the console by wrapping our call of our function with print().
print(someFunc(name: "Fathima"))
Leave a Reply