How to write a function in Swift

First time here? Get started in my Swift guide.


Functions are coded to perform actions and manipulate variables. They are part of a core component in programming. In Swift, functions are very simple to write and, if you have a basis of Object Oriented Programming, you can reuse them throughout your program.

Functions are used in all sorts of programs. You can write a function to calculate the number of calories you ate this morning (I ate a lot, btw), how many miles you should run to burn them or even if you can purchase a book using your credit card!

Defining a function

In Swift and other programming languages, a function is defined by using the func keyword followed by its name, optional parameters, execution path and a return value.

So, let me illustrate that:

func nameOfFunction(parameterA: Int, parameterB: Int) -> Int {


//Now, what do you want the function to perform?

//I wrote a function that will return an integer


//Let's say you want to sum both parameters, which are integers.

return parameterA + parameterB

}

The function will return the sum of both integers. There’s no big deal or complex syntax when you write a function with parameters in Swift. Of course, you could have written such function in many different ways – that’s really up to you.

If you want to see that function running or write your own, all you have to do is open up Xcode and start a new playground. Yes, you need a Mac for that, unless you want to learn this trick.

Now, let’s understand the whole format of a Swift function.

See that -> Int right after the parameters’ parenthesis? It means that the function will (and must, otherwise it will crash) return an integer. Again, that’s up to you – a function could return an Int, Double, String…

Now, let’s say you want to find the hypotenuse of that beautiful right-triangle.

1200px-Rtriangle.svg.png
Thanks a lot, Wikipedia

 So, how would you start writing the function to return its hypotenuse (c)?

Start by writing down the variables you need to calculate it. You need both legs of the triangle:

  • legA
  • legB

Would you declare them as Int or Double? Well, as a tip to avoid crashes, you want to declare them as Double

Now, as we have two legs of the right-triangle, how should we calculate its hypotenuse?

a² + b² = c² 

Thanks a lot, Pythagoras.

Now, we start just as we did in the previous function:

func findHypotenuse(legA: Double, legB: Double) -> Double {

So, why such syntax – findHypotenuse? When writing the name of a function, variable or constant with multiple words, there’s a convention to have the lower case in the first word. Your code may not crash if you don’t follow such convention, but it helps keeping your code clean and easier to read.

Again, we passed as parameters what the function needs to know to perform the task – legA and legB. The following path (-> Double) will have the function to return a Double value. 

Now, let’s write our equation. Here’s one possibility to write it:

  • Create a constant named hypotenuse (let hypotenuse)
  • Do the math as a result to such constant

But why use a constant for hypotenuse value? Ask yourself: when you run your code, will ever the hypotenuse change values? It won’t, so we shall use let.

let hypotenuse = sqrt(pow(legA, 2) + pow(legB, 2))

pow(a, b) is a library function, meaning that it was already written and Swift knows exactly how to execute it. is the number you want raise to a given power b. Minding all parenthesis, sqrt will return the square root of the value inside its parenthesis.

Here’s how our function will look:

func findHypotenuse(legA: Double, legB: Double) -> Double {

let hypotenuse = sqrt(pow(legA, 2) + pow(legB, 2))

return hypotenuse
}

Now, to run your function you simply need to call it and assign your parameters:

findHypotenuse(legA: 3, legB: 4)

Here’s how it looks in your Xcode Playground:

Screen Shot 2018-01-23 at 5.08.45 PM

Easy, right?


So, excited for Swift?

Jump in my exclusive email newsletter and I will send you one email per week (that’s right, no spam) with tips, tutorials and a sneak-peek on paid projects I develop.

Just click here and subscribe

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s