Functions

Last updated on 27 Oct 2024.

Written by Jia Chen.

Functions

Last updated on 27 Oct 2024.

Written by Jia Chen.

Functions

Last updated on 27 Oct 2024.

Written by Jia Chen.

Scroll Down

On this page

On this page

What is a Function?

Functions are self-contained chunks of code that perform a specific task. You can supply functions with additional parameters to customize functionality.

Declaring Functions

func sayHello() {
    print("Hello! I am Jia Chen")
}

Calling Functions

To execute the code within a function, you have to call the function.

sayHello() // Prints "Hello! I am Jia Chen!"

Functions with Parameters

Parameters allow you to inject value(s) into the function.

When declaring a parameter, you have to provide an explicit type for the value.

(parameterName: Type)

In the following example, the sayHello() function can be modified to inject a name value. This allows the sayHello() function to be reused for different names.

func sayHello(name: String) {
    print("Hello! I am \(name)!")
}

To call the function, you will now have to supply the function with the name parameter.

sayHello(name: "Jia Chen") // Prints "Hello! I am Jia Chen!"
sayHello(name: "YJ") // Prints "Hello! I am YJ!"
sayHello(name: "Sean") // Prints "Hello! I am Sean!"

Multiple Parameters

Multiple different parameters can be declared, separated by commas. This allows you to inject multiple different values into the function.

func myFunctionName(parameterName: Type, anotherParameterName: Type) { ... }

In the following example, an additional hobby String value is also injected into the function.

func sayHello(name: String, hobby: String) {
    print("Hello! My name is \(name)!”)
    print("My hobby is \(hobby)!”)
    print("Bye!")
}

Likewise, when you call the function, you will have to also supply it with the hobby parameter.

sayHello(name: "Jia Chen", hobby: "Writing Tutorials")
sayHello(name: "Sean", hobby: "Keyboards")

Argument Labels

An argument label is a variable name that you provide in the function declaration to be used when the function is called. Swift heavily emphasizes writing readable code that sounds as similar to English as possible.

You can see the argument label as the "public name" and the parameter name as the "internal name".

You can declare an argument label by supplying one preceding the parameter name.

func myFunctionName(argumentLabel parameterName: Type) { ... }

In the following example,

  • the parameter name, name, has an argument label of for, and

  • the parameter name, hobby, has an argument label of withHobby.

Naming a variable for or withHobby might not make sense within in your code, but when used as part of the function, it helps to make the statement more readable.

func sayHello(for name: String, withHobby hobby: String) {
    print("Hello! My name is \(name)!”)
    print("My hobby is \(hobby)!”)
    print("Bye!")
}

When you call the function, the argument label is used instead of the parameter name.

sayHello(for: "Jia Chen", withHobby: "Writing Tutorials")
sayHello(for: "Sean", withHobby: "Keyboards")

Omitting Argument Labels

You can omit an argument label entirely by supplying an underscore (_) as the argument label name.

func sayHello(_ name: String, withHobby hobby: String) {
    print("Hello! My name is \(name)!”)
    print("My hobby is \(hobby)!”)
    print("Bye!")
}

When calling this function, you do not need to use an argument label for the name parameter.

sayHello("Jia Chen", withHobby: "Writing Tutorials")
sayHello("Sean", withHobby: "Keyboards")

Function Types

Like variables, functions can also have types. This allows the function to evaluate and return a result.

To declare a function with a type, add a -> followed by the type name after the function's parameters.

func myFunctionName(parameterName: Type) -> ReturnType { ... }

If there are no parameters, add the return type after the parenthesis.

func myFunctionName() -> ReturnType { ... }

In the following example, the calculateBMI function takes in 2 values—a weight (in kilograms) and height (in meters), calculates the body mass index, and returns the value.

func calculateBMI(weight: Double, height: Double) -> Double {
    let bmi = weight / (height * height)
    return bmi
}

Implicit Return

If the function only contains a single line, the return keyword can be omitted. This is called an implicit return as Swift infers that the only line is the returned value.

func calculateBMI(weight: Double, height: Double) -> Double {
    weight / (height * height)
}

Functions & SwiftUI

Functions can be used within SwiftUI to help break down large chunks of conditional logic or break apart large views.

Creating a Function in SwiftUI

When creating a function within SwiftUI, it is best to declare it outside of the view's body Computed Property, while still within the view structure.

struct ContentView: View {
    var body: some View {
        ...
    }
  
    func doSomething() {
        ...
    }
}

Calling the Function within SwiftUI

By default, a function is Logical Code. It can only be used within places like a Button's action or with the onAppear modifier. Calling a function in SwiftUI is exactly the same as calling a function within Swift.

Button("Run Function!") {
    doSomething()
}
.onAppear {
    doSomething()
}

Using a Function as an Action

Functions can be supplied directly to controls like Buttons as actions.

In the following example, the Button to run the doSomething function when tapped and a similar example with the onAppear modifier.

Button("Hello", action: doSomething)
.onAppear(perform: doSomething)

Breaking Large Views with Functions

Functions can be used to break up large view files into smaller functions.

By setting the function's type as some View, the function can return View Builder code, allowing it to be used as part of composing your interface.

The following example shows how a function can be used to apply repeated modifiers on a text, reducing the amount of repeated code.

struct ContentView: View {
    var body: some View {
        VStack {
            createText("Welcome")
            createText("Hello, User!")
        }
    }

    func createText(_ content: String) -> some View {
        Text(content)
            .font(.title)
            .padding()
    }
}

© 2024 Tinkertanker Pte Ltd / Swift Accelerator. All rights reserved.

© 2024 Tinkertanker Pte Ltd / Swift Accelerator. All rights reserved.

© 2024 Tinkertanker Pte Ltd / Swift Accelerator. All rights reserved.