Functions in Swift

In Swift, functions are the primary way to perform tasks. Each function is a set of statements organized together to do something meaningful. For someone new to Swift, understanding functions is crucial as they form the backbone of any Swift program, from simple apps to complex systems.

article

In Swift, functions are the primary way to perform tasks. Each function is a set of statements organized together to do something meaningful. For someone new to Swift, understanding functions is crucial as they form the backbone of any Swift program, from simple apps to complex systems.


What are Functions


A function is a reusable, self-contained block of code designed to perform a specific task. In Swift, its syntax is both flexible and expressive, making functions incredibly powerful. Let's look at the following example:


        
func sayHello() {
    print("Hello, world!")
}
        
    

This function, sayHello, takes no parameters and has no return value. It simply prints "Hello, world!" to the console. To execute the function, you call it by its name followed by parentheses:


    
 sayHello() // This will print "Hello World in our console"
    

Let's play around with a new function. In this function we add 2 parameters and we also add a return value. This makes sure that the function only returns a certain type.

    
func add(a: Int, b: Int) -> Int {
    return a + b
}
let result = add(a: 5, b: 3)  // result is 8
    

Here, 'add' is a function that takes two integers as input and returns their sum as an integer.


Methods in Swift


In Swift, methods are simply functions associated with a class, struct, or enum. They provide functionality for instances of those types or for the type itself if marked as 'static'.


    
class Pokemon {
    var name: String
        
    init(name: String) {
       self.name = name
    }
            
    func display() {
        print("Pokémon: \(self.name)")
    }
}
        
    let pikachu = Pokemon(name: "Pikachu")
    pikachu.display()  // Outputs: Pokémon: Pikachu
    

In this example, display is a method of the Pokemon class, allowing any Pokemon instance to print its name.


Static Functions in Swift


Static functions belong to the type rather than any instance of the type. They are called on the type itself.


    
class Calculator {
    static func square(number: Int) -> Int {
        return number * number
    }
}
        
Calculator.square(number: 4)  // Outputs: 16
    


Static functions are useful for utility functions that operate independently of instance properties.


@objc Functions: Bridging Swift and Objective-C


The @objc attribute exposes Swift functions to Objective-C. This is necessary in projects that use Objective-C frameworks or in mixed-language projects like older iOS projects from before 2014.


    
class Calculator {
    static func square(number: Int) -> Int {
        return number * number
    }
}
        
Calculator.square(number: 4)  // Outputs: 16
    

Here, printMessage can be called from Objective-C code because of the @objc attribute. This interoperability is crucial for developers working with legacy code or utilizing Apple’s vast Objective-C based frameworks.


Practical Example in Swift: Using Functions with Pokémon


To fully grasp the power of functions in Swift, let’s dive into a more practical application. Imagine you're building a Swift app to catalog Pokémon. Functions, methods, and static functions will be your tools for managing the Pokémon data.


    
struct Pokemon {
    var name: String
    var type: String
            
    func displayInfo() {
       print("Name: \(self.name), Type: \(self.type)")
    }
}
        
    let charmander = Pokemon(name: "Charmander", type: "Fire")
    charmander.displayInfo()  // Outputs: Name: Charmander, Type: Fire 
    

In this scenario, displayInfo is a method that provides functionality for Pokemon instances, allowing each Pokémon to print its own information.


Conclusion


Functions in Swift, whether standalone, part of a type (methods), static, or bridging to Objective-C (@objc), form the core of Swift programming. They encapsulate tasks, making your code more modular, reusable, and easy to read. The key to mastering Swift functions lies in understanding these different types and their applications, from structuring your app’s logic with simple functions and methods to integrating Swift with Objective-C frameworks using @objc. As you experiment with and implement functions in your Swift projects, you'll discover their power and flexibility, essential for becoming a proficient Swift developer.


This article touches only the surface of what's possible with Swift functions. The journey from here involves diving deeper into each aspect, experimenting with code, and building your understanding of Swift's capabilities. Whether you're cataloging Pokémon or building the next great iOS app, functions will be at the heart of your Swift programming endeavors.

instructor

Exodai INSTRUCTOR!

Johan t'Sas

Owner and Swift developer!