Functions: Free iOS Development Tutorial

Learn how to effectively utilize functions in iOS development, including defining parameters, passing arguments, and using multiple parameters in a single function with our detailed tutorial.

This exercise is excerpted from Noble Desktop’s past app development training materials and is compatible with iOS updates through 2021. To learn current skills in web development, check out our coding bootcamps in NYC and live online.

Note: These materials are provided to give prospective students a sense of how we structure our class exercises and supplementary materials. During the course, you will get access to the accompanying class files, live instructor demonstrations, and hands-on instruction.

Topics covered in this iOS Development tutorial:

Simple functions, Defining parameters & passing arguments, Using multiple parameters in a single function, Returning parameters, Tuples

Exercise Overview

Much of what you’ll be doing as a programmer is writing functions and other structures. Functions in Swift are reusable blocks of code that are used to perform specific actions. There are built-in functions that Apple provides, such as the print function from the previous exercises. Additionally, you can create your own custom functions, which is what we’ll explore in this exercise.

In this exercise, you’ll learn how to code simple custom functions, as well as functions that take additional info or return something. You’ll also learn how to write a function that returns multiple values by combining them into a single value.

Full-Stack Web Development Certificate: Live & Hands-on, In NYC or Online, 0% Financing, 1-on-1 Mentoring, Free Retake, Job Prep. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

Getting Started

  1. Launch Xcode if it isn’t already open.

  2. Go to File > New > Playground.

  3. Under iOS, double–click Blank.

  4. Navigate into Desktop > Class Files > yourname-iOS App Dev 1 Class.

  5. Save the file as: Functions.playground

  6. Click Create.

Simple Functions

Functions are used to group together lines of code that perform a specific task at a desired time. You can then call this function later, telling the program to execute the task defined in the function. This task can be run repetitively, potentially using different information each time it runs.

  1. In Xcode, replace the var str line with the bold custom function:

    import UIKit
    
    func play() {
    
    }
    
  2. The code that you want your function to execute goes inside the curly braces { }. Flesh out the custom function by adding the following bold code:

    func play() {
       print("The game has started")
    }
    
  3. Let’s take a closer look at the syntax. We declared a function with the name play. Declaring a function defines what it does, but does not execute the code inside the curly braces (as you can see by the lack of output in the Playground results sidebar on the right).

  4. Now that we’ve declared a function, let’s use it. Add the bold code to call our custom function, printing the string inside the built-in print function:

    func play() {
       print("The game has started")
    }
    
    play()
    
  5. Look in the Playground results sidebar on the right, to see that our function prints: The game has started

Defining Parameters & Passing Arguments

  1. It’s often necessary to pass information into a function. To do this, we can give it parameters. As shown, declare a function that takes a String variable as a parameter:

    func play() {
       print("The game has started")
    }
    
    func namePlayer(playerName: String) {
    
    }
    
  2. Our function is named namePlayer, and takes a string variable called playerName. It’s written as namePlayer(variable: Type) because it takes a parameter of the specified data type (String in this case). To finish, add the bold print function:

    func namePlayer(playerName: String) {
       print("Your player is now named \(playerName)")
    }
    
  3. While a function’s parameters ask for information, the pieces of info we pass to it are called arguments. Let’s execute the function and name the player. Before the play function call, call the namePlayer function by passing in a string as an argument:

    func namePlayer(playerName: String) {
       print("Your player is now named \(playerName)")
    }
    
    namePlayer(playerName: "Johnny")
    
    play()
    
  4. Take a look at the syntax, which uses the format:
    functionName(parameterName: argument).

    When you’re passing arguments into a function that takes a parameter, you need to fill in the function’s parentheses by typing the parameter name followed by the argument you are passing in. This helps you remember which parameter is asking for the information you are specifying by passing in an argument.

  5. On the right of Xcode, you should see: Your player is now named Johnny. We passed the playerName value into the function when it was called.

  6. Let’s reuse the function by passing in another name as an argument. Call the function again with another player name:

    namePlayer(playerName: "Johnny")
    namePlayer(playerName: "Michelle")
    
  7. On the Xcode sidebar you’ll see it says (2 times) for each time the function was called. Click the Debug area icon show hide debug area on the top right of Xcode to see that the console has printed the string using each playerName we passed in as arguments.

Using Multiple Parameters in a Single Function

Sometimes we need to define a function with more than one parameter. For example, to calculate the area of a given room we’d want to pass in arguments for length and width.

  1. Let’s create a new function that inputs multiple parameters. Below the other functions you wrote, type:

    func setPlayerAttributes(hairColor: String, height: Int) {
    
    }
    
    namePlayer(playerName: "Johnny")
    
  2. We just created a function called setPlayerAttributes and gave it a couple parameters. Finish the function by adding the following bold print function:

    func setPlayerAttributes(hairColor: String, height: Int) {
       print("Your player's hair is \(hairColor) and their height is \(height) feet")
    }
    
  3. Above the play function call, call the new function by passing in two arguments. As you type the bold code shown below, Xcode will give you handy code hints for where to put your arguments (by indicating the parameters you just defined and their data types). Tab through and it’ll highlight the section to type in.

    setPlayerAttributes(hairColor: "Blonde", height: 6)
    
    play()
    
  4. Notice in the sidebar it says: Your player’s hair is Blonde and their height is 6 feet

  5. Let’s take a closer look at how parameter order affects how you pass in arguments when calling a function with multiple parameters. In the setPlayerAttributes function definition in the middle of the code, swap its parameters around as shown in bold:

    func setPlayerAttributes(height: Int, hairColor: String) {
       print("Your player's hair is \(hairColor) and their height is \(height) feet")
    }
    
  6. Near the bottom of the file, notice where we called our function. There’s a red alert red circle error icon. Click it.

    The handy pop-up will tell you that the argument for the 'height' parameter must come before the argument for 'hairColor'.

  7. Red errors with a circle in the middle provide a helpful Fix-it suggestion. Click the Fix button.

  8. The error should disappear, and your code should now look like this:

    setPlayerAttributes(height: 6, hairColor: "Blonde")
    

Returning Parameters

  1. In addition to passing parameters into a function, we can tell a function to give a parameter back. We’ll define a function that returns a parameter. Start creating a new function with the bold code:

    func setPlayerAttributes(height: Int, hairColor: String) {
       print("Your player's hair is \(hairColor) and their height is \(height) feet")
    }
    
    func score()
    
    namePlayer(playerName: "Johnny")
    

    NOTE: You will see a red alert red alert icon. Don’t worry, it will go away once we finish coding up the function.

  2. We won’t be passing in a parameter, but instead we want to receive a parameter back. To do this, type:

    func score() -> Int {
    
    }
    

    Here we are using a return arrow (->) to indicate the function’s return type. This function will expect an integer because you specified Int. You can return any data type, as long as it’s specified.

  3. To get rid of the red alert, we need to add a return statement with the value we want our function to return. Let’s set the score to be 20. Type:

    func score() -> Int {
       return 20
    }
    
  4. Now call the score function and it will return 20:

    setPlayerAttributes(height: 6, hairColor: "Blonde")
    
    play()
    score()
    
  5. This works, but a better and more real-world way of doing this would be to create a variable and set it to the return value from our function. Modify the code as shown:

    var currentScore = score()
    
  6. We pass the score return into a variable so we can do something like this:

    var currentScore = score()
    print("The score is now \(currentScore)")
    

Tuples

You can return multiple values in a function. This group of values combined into a single value is called a tuple. The individual values in a tuple can be of any type, and you can mix data types inside a tuple, such as String, Double, etc.

  1. Under the other functions you defined, start creating the function (you’ll get a red error for a few steps):

    func playerHistory()
    
    namePlayer(playerName: "Johnny")
    
  2. Again, you won’t be passing in parameters here, but you want to receive them back. Add the following bold return types to the function:

    func playerHistory() -> (topScore: Int, numberOfGames: Int) {
    
    }
    

    To use a tuple as a return type, we place comma-separated parameters in parentheses (). While we are returning two parameters of the Int data type in this function, keep in mind that the values inside a tuple don’t need to be the same type.

  3. To get rid of the red error, add the following bold return statement to set topScore to 1000 and numberOfGames to 10:

    func playerHistory() -> (topScore: Int, numberOfGames: Int) {
       return(topScore: 1000, numberOfGames: 10)
    }
    
  4. Let’s do two things in order to use the function we just created. First, go to the bottom of the file and assign the return value to a constant, as shown:

    print("The score is now \(currentScore)")
    
    let history = playerHistory()
    
  5. In the sidebar on the right, it should say (.0 1000, .1 10). Tuples keep track of their multiple parameters by numbering them. Like lots of other coding languages such as JavaScript, this numbering starts with zero instead of one. So this means that the first (0) parameter has a value of 1000, and the second (1) parameter has a value of 10.

  6. Finish using the function by printing the results:

    let history = playerHistory()
    print("The high score is \(history.topScore) for a total of \(history.numberOfGames) games")
    
  7. Let’s break that down:

    • We took the playerHistory return value from the function and assigned it to a constant named history.
    • To access individual values within a tuple, we use the following convention (using dot syntax): (constantName.parameter).
  8. Look in the results sidebar on the right to see that both values in the tuple are included in the output: The high score is 1000 for a total of 10 games

  9. Save and close the file. Keep Xcode open, as we’ll use it in the next exercise.

How to Learn iOS & Web Development

Master iOS development, web development, coding, and more with hands-on training. iOS development involves designing apps for Apple mobile devices with tools like Xcode and SwiftUI.

Yelp Facebook LinkedIn YouTube Twitter Instagram