Understanding Functions

Functions are a way to run your code on demand. You briefly explored functions in an earlier lesson. When associated with objects, functions are also known as methods. You used a function to print out a message. Functions do far more than that.

Functions also take in values and may return a value. For instance, an addition function may receive two integers. It will combine those integers and return the result.

When defining a function, you first define the inputs. You can pass whatever you like into the function. You simply define the variables in the function header:

func printName(firstName: String, lastName: String) {

}

This function requires two strings. When defining the parameters, you must always define the type. In this case, the function takes two strings but doesn’t return a value. You provide a return type before the opening curly brace.

func printName(firstName: String, lastName: String) -> String {

}

For the return type, you add an arrow (->) followed by the type. You don’t need to give it a name.

This function unfortunately does not work. This is because it is not returning anything. You must use the return keyword.

func printName(firstName: String, lastName: String) -> String {
    return "\(firstName) \(lastName)"
}

You can use multiple return keywords in a single function. It is often the last statement in a function, but you can use it to “leave early”. If you do return out of a function early and that function returns a value, you must return a value.

See forum comments
Download course materials from Github
Previous: Demo: Looping in SwiftUI Next: Demo: Adding SwiftUI Functions