Create a Function in Swift

Functions are a very important concept in programming. They allow us to write code once, and run it as many times as we want. As the official documentation states, “Functions are self-contained chunks of code that perform a specific task”. In this tutorial, you will learn how to create functions in Swift and how you can use them to reuse code and functionality.

If you are interested in video lessons on how to write Unit tests and UI tests to test your Swift mobile app, check out this page: Unit Testing Swift Mobile App

Creating a new function

I’ll create a simple function that just prints the String “Hello World from Apps Developer Blog” on the console.

 // Declare a function
func sayHelloWorld() {
    print("Hello World from Apps Developer Blog")
}

// Call function
sayHelloWorld()

In Swift, you declare a function with the func keyword. After that, you need to provide a name to the function, followed by ( , it’s parameters (if any), and ). In this example, you only print a String into the console, but you can use a function to store more complex functionality that you can later reuse, instead of rewriting it every time you need it.

Another benefit of using functions is that when you need to update the repetitive functionality, you only need to modify the content of the function, instead of looking into your code, finding the places where you hard-coded that functionality, and hoping that you changed it in every place that you use it.

With functions, you write the code once, use it everywhere you want, and if you need to update it, there’s only one place that you need to modify to see the reflected changes.

Methods

In Swift, methods are just functions that are associated with a class. In our previous blog post, you learned how to create a class in Swift, and even you added a method to it. Let’s review it.

class Person {
    var firstName: String
    var lastName: String
    
    // initializer method
    init(firstName: String, lastName: String) {
        self.firstName = firstName
        self.lastName = lastName
    }
    
    func getFullName() -> String {
        return firstName + " " + lastName
    }
}
let person = Person(firstName: "Sergey", lastName: "Kargopolov")
print("Full name: " + person.getFullName())

The getFullName method is just a function associated with the Person class. Methods are functions that are aware of the context they’re inside in. The getFullName method accesses the firstName and lastName stored properties of the Person class, and return a formatted string concatenating them.

Difference Between a Function and a Method in iOS Swift

In Swift, a function and a method both refer to reusable pieces of code, but they have a subtle distinction. A function is a standalone block of code that performs a specific task and can exist independently. On the other hand, a method is a function that is associated with a specific class or type.

Think of a function as a general tool you can use anywhere, while a method is a specialized tool that belongs to a particular object or class. So, when you create a function, it’s like having a tool in your toolbox, and when you create a method, it’s like customizing that tool for a specific job in your workshop (class or struct).

Can I use a function outside of a class or struct?

Absolutely! In Swift, functions can exist independently without being tied to a class or struct. These standalone functions are often referred to as global functions because they are not associated with any specific class or type, just like the print function. You can think of them as versatile tools that can be used anywhere in your codebase.

This flexibility allows you to create reusable code snippets that are not bound to a particular context, making them handy for various tasks throughout your projects.

A function inside another function in iOS Swift

In Swift, you can create a function inside another function, and so, is called a nested function. This concept is like having a toolbox within a toolbox – a specific set of tools designed for a particular job, neatly tucked inside a larger toolset. The primary advantage of nested functions is that they are scoped within the enclosing function, making them accessible only from within that function.

func outerFunction() { 
    // Outer function code 
    func innerFunction() { 
    // Inner function code 
    } 

    // Calling the nested function 
    innerFunction() 
} 

// Calling the outer function 
outerFunction()

In this example, innerFunction is defined inside outerFunction. It can access variables and parameters from its enclosing function (outerFunction), providing a way to modularize and compartmentalize code. This can be particularly useful when you have a specific task that is relevant only within a certain context.

Using nested functions in Swift can greatly enhance code readability, especially for beginners. Unlike private functions, which can still be accessed elsewhere inside the class, nested functions are confined within the specific function where they are declared. This creates a clear boundary, signaling other developers (and even your future self!) that these functions are exclusive to their parent function, making the code more self-contained and easier to understand.

Another advantage is encapsulation. Nested functions can access all the local parameters of their parent function, eliminating the need to pass them around. This not only reduces the complexity of your code but also means fewer functions to test. Embracing nested functions is a smart way to maintain code cleanliness and improve your overall development workflow.

For a more in-depth exploration of nested functions and their practical applications, you can check another tutorial about Creating and Using Nested Functions in Swift.

A Function as a Return Value in iOS Swift

Aside from declaring nested functions and using them inside of the parent function, you can even return them and use them later on in your code. In Swift, you can return a function as a value from another function. This concept is often referred to as closures. Essentially, you’re handing out a fully packaged piece of functionality for others to use.

Consider the following example:

func simpleGreeting() -> () -> String {
    func greet() -> String {
        return "Hello, Swift Learner!"
    }
    return greet
}

let greetingFunction = simpleGreeting()

let greetingMessage = greetingFunction()
print(greetingMessage)  // Output: Hello, Swift Learner!

This concept is powerful because it allows you to encapsulate and distribute specific pieces of functionality. Understanding how to return functions as values opens up new possibilities for designing clean and modular code in your iOS Swift projects.

If you’re intrigued to explore more about closures in Swift, check out our dedicated tutorial Declare a Closure in Swift.

Creating a function to reuse functionality on UIKit’s UIViewController

When you create an app, setting the background color to a UIViewController‘s view is really common, but what if you want a custom gradient as a background? What if you want multiple screens to share the same gradient as a background? You could just copy and paste code from one UIViewController to the other, but that would be a problem if you later on what to make changes to the gradient (change colors, orientation, etc). You’ll need to update the code in every view you use it.

A more modular and cleaner solution would be to create a function that sets up the gradient, and we can reuse it every UIViewController we want. That goal can be easily achieved with the help of class extensions and methods (which you already learned, are just functions associated with a class).

import UIKit

extension UIViewController {    
    func setupGradientBackground() {
        let topColor = UIColor.systemPink
        let bottomColor = UIColor.systemCyan
        let gradientLayer = CAGradientLayer()
        
        gradientLayer.colors = [topColor.cgColor, bottomColor.cgColor]
        gradientLayer.locations = [1, 0]
        gradientLayer.frame = view.frame
        
        view.layer.addSublayer(gradientLayer)
    }
}

In the above code snippet, you extend the UIViewController class and create a method called setupGradientBackground. That method is charged with the responsibility of creating a CAGradientLayer (a class provided by Core Animation for creating gradient layers) property, creating and setting its colors and their location in the gradient, and the frame of the gradient layer to match the frame of the view controller’s view. Now you can set up a nice and pretty gradient layer to any view controller background we want.

function example

If you later on decide that UIColor.systemPink and UIColor.systemCyan colors don’t represent the design that you want, you’ll need to only update the setupGradientBackground method and the changes will be reflected on the entire app.

Conclusion

Functions are a very powerful tool that any programmer should have on their belt. They allow code reusability and modularity, helping to organize related functionality and overall getting a cleaner code.

To learn more about functions in Swift have a look at this larger tutorial: Swift functions tutorial.

Leave a Reply

Your email address will not be published. Required fields are marked *