Functions
Definition and use.
Functions
Definition and use.
0
0
Checkbox to mark video as read
Mark as read

What is a function and what is it used for?

A function is a block of code that we can execute at any time from anywhere in our code. This helps us avoid code repetition and also organize it better.

Let’s see an example where we have several buttons on the screen, all of which need to perform the same action when pressed. Therefore, we can declare a function that will be executed by each button.

@State var counter: Int = 0

var body: some View {
    VStack {
        Text("\(counter)")

        Button(action: {
            incrementCounter()
        }, label: {
            Text("Button 1")
        })

        Button(action: {
            incrementCounter()
        }, label: {
            Text("Button 2")
        })

        Button(action: {
            incrementCounter()
        }, label: {
            Text("Button 3")
        })
    }
}

func incrementCounter() {
    counter += 1
    if counter == 10 {
        counter = 0
    }
}

Instead of writing the same code multiple times for each button, we’ve declared a function that includes this code only once.

Declare a function using the following pattern:

  • The keyword func
  • A name you choose for the function (two functions cannot have the same name).
  • Parentheses ()
  • A block of code enclosed in curly braces { }

Execute the function using the following pattern:

  • The function name.
  • Parentheses ()

Parameters

We can also declare variables in a function, and these variables are called parameters. These parameters will only be accessible within the function.

func incrementCounter(amount: Int) {
    counter += amount
    if counter == 10 {
        counter = 0
    }
}

To execute this function, we need to assign a value to each parameter.

Button(action: {
    incrementCounter(amount: 1)
}, label: {
    Text("Button 1")
})

Button(action: {
    incrementCounter(amount: 2)
}, label: {
    Text("Button 2")
})

Button(action: {
    incrementCounter(amount: 3)
}, label: {
    Text("Button 3")
})

In this way, each button can increase the counter differently while sharing the same code.


func myFunction(paramOne: Int, paramTwo: String) {
    // Code block
}

myFunction(paramOne: 23, paramTwo: "My String")

Return

A function can also return a value. To do this, we use the return keyword, and we must declare what type of variable will be returned:

func squareOf(number: Int) -> Int {
    var result = number * number
    return result
}

var square: Int = squareOf(number: 3) // The result is 9

Let’s review the new elements of this example of a function where we pass a number as a parameter, and it returns the square of that number:

  • We declare what type of value will be returned with -> Int.
  • We return the desired value.

Using functions in a view

We can create functions within our views to better organize our code. To do this, we declare -> some View as the return type (we will explore what this means later).

@State var shoppingList: [String] = [
    "Tomatoes",
    "Potatoes",
    "Chicken",
    "Salmon",
    "Water",
    "Pizza"
]

var body: some View {
    List {
        ForEach(0..<shoppingList.count, id: \.self) { i in
            item(i: i)
        }
    }
}

func item(i: Int) -> some View {
    HStack {
        Text("\(i + 1): ")

        Text(shoppingList[i])
            .font(.headline)
    }
}

course

Quiz Time!

0 Comments

Join the community to comment
Sign Up
I have an account
Be the first to comment

Accept Cookies

We use cookies to collect and analyze information on site performance and usage, in order to provide you with better service.

Check our Privacy Policy