Home

A Quick Intro to Swift Functions

|
|  Updated:  
2022-08-10 16:44:34
Android App Development For Dummies
Explore Book
Buy On Amazon
Are you ready to build iOS apps using an innovative and intuitive user interface? Then, SwiftUI is for you! But before you dive in, you’ll need to know about Swift functions. Here’s a quick intro.

SwiftUI app development ©Shutterstock/baranq

In Swift, a function is defined using the func keyword, like this:

func doSomething() {
   print("doSomething")
}
The preceding code snippet defines a function called doSomething. It does not take in any inputs (known as parameters) and does not return a value (technically, it does return a Void value).

To call the function, simply call its name followed by a pair of empty parentheses:

doSomething()

Understanding input parameters

A function can also optionally define one or more named typed inputs. The following function takes in one single typed input parameter:
func doSomething(num: Int) {
    print(num)
}
To call this function, call its name and pass in an integer value (known as an argument) with the parameter name, like this:
doSomething(num: 5)
The following function takes in two input parameters, both of type Int:
func doSomething(num1: Int, num2: Int) {
    print(num1, num2)
}
To call this function, pass it two integer values as the argument:
doSomething(num1: 5, num2: 6)

Returning a value

Functions are not required to return a value. However, if you want the function to return a value, use the -> operator after the function declaration. The following function returns an integer value:
func doSomething(num1: Int, num2: Int, num3: Int) -> Int {
    return num1 + num2 + num3
}
You use the return keyword to return a value from a function and then exit it. When the function returns a value, you can assign it to a variable or constant, like this:
var sum = doSomething(num1:5, num2:6, num3: 7)

Functions are not limited to returning a single value. In some cases, it’s important for functions to return multiple values (or even functions). In Swift, you can use a tuple type in a function to return multiple values.

Want to learn more? Check out these SwiftUI tips and tricks.

About This Article

This article is from the book: 

About the book author:

Wei-Meng Lee is founder of Developer Learning Solutions, specializing in hands-on technology training. His name regularly appears in publications like DevX.com, MobiForge.com, and CODE Magazine. He is also the author of SwiftUI For Dummies, Beginning Swift Programming, Python Machine Learning, and Learning WatchKit Programming.