Swift Programming – Methods

In this tutorial you’ll learn about methods in Swift. To follow along, it is recommended to have a Mac and the Xcode IDE installed on it. This tutorial makes use of the Xcode playground for compilation of the Swift codes. If you do not have a Mac, you may try using the open-source code editors which support different operating systems such as AtomSublimeText or VSCode.

Methods

Methods are functions that we can write inside a class, a structure or an enumeration. We can work with the instance methods that we defined in a class, a structure or an enumeration, in an instance of a given type.

Instance Methods

The instance of a class, a structure or an enumeration can provide instance methods (functions) that we defined in that specific class, structure or enumeration.

class Person {
    var name: String = ""
    
    func calculateAge(given yearBorn: Int) -> Int {
        let calendar = Calendar.current
        let currentDate = Date()
        let currentYear = calendar.component(.year, from: currentDate)
        
        return currentYear - yearBorn
    }
}
let person = Person()
let age = person.calculateAge(given: 1993)
print("Calculated age is \(age) years old")

In our example above, we defined a class with the name Person, one stored variable property name and an instance method calculateAge(given:).

The self Property

There is an implicit self property in each instance of a type, that refers to the instance itself.

class Animal {
    var multiplier: Int = 5
    
    func multiply(with number: Int, by multiplier: Int = 5) -> Int {
        return number * self.multiplier
    }
}
var animal = Animal()
var number = 9
var result = animal.multiply(with: number)
print("Multiplication of \(number) with \(animal.multiplier)")
number = 15
result = animal.multiply(with: number, by: 6)
print("Multiplication of \(number) with \(animal.multiplier)")

In our example above, we have a stored variable property multiplier with a default value of 5. We used the instance method multiply(with:by:) twice. In the first call, we provided a value for the first parameter and in the second call we provided values for both parameters. Notice that we defined the second parameter of our method with the same name as our stored property. Our method is returning a multiplication of the parameter number by the stored property multiplier. Since we have a parameter bearing the same name as our stored property, we have to provide a way for Swift to distinguish which of these two values we are interested in. To do that, we prepended our stored property multiplier with a self.. Now notice that in our second call of the method, we are not really using it in our multiplication.

Modifying Value Types from Within Instance Methods

In order to solve our previous example’s problem, we can assign the stored property multiplier to the parameter’s multiplier‘s value. That way we are updating the stored property multiplier every time we provide a new multiplier in our instance method’s call. However, we have another problem. Structures are value types, therefore we are not allowed to modify a property value via an instance method. To solve this problem, we should use the keyword mutating in our method’s definition.

struct Animal {
    var multiplier: Int = 5
    
    // Modifying Value Types from Within Instance Methods
    mutating func multiply(with number: Int, by multiplier: Int = 5) -> Int {
        self.multiplier = multiplier
        return number * self.multiplier
    }
}
var animal = Animal()
var number = 9
var result = animal.multiply(with: number)
print("Multiplication of \(number) with \(animal.multiplier) is \(result)")
number = 15
result = animal.multiply(with: number, by: 6)
print("Multiplication of \(number) with \(animal.multiplier) is \(result)")

Type Methods

You can provide type methods in a class, a structure or an enumeration. You indicate a type method by writing the keyword static before the keyword func. In order for a class to provide a way for its subclasses to implement its type method, replace the keyword static with class.

struct MathOperation {
    static func sum(_ numbers: Int...) -> Int {
        var sum = 0
        
        for number in numbers {
            sum += number
        }
        return sum
    }
    
    static func subtract(first: Int,  with second: Int) -> Int {
        first - second
    }
    
    static func multiply(first: Int, by second: Int) -> Int {
        first * second
    }
    
    static func divide(first: Double, by second: Double) -> Double {
        first / second
    }
}
let addition = MathOperation.sum(2, 5, 9, 88, 100, 123, 16, 77)
let subtraction = MathOperation.subtract(first: 125, with: 66)
let multiplication = MathOperation.multiply(first: 12, by: 5)
let division = MathOperation.divide(first: 35, by: 5)

Reference

https://docs.swift.org/swift-book/LanguageGuide/Methods.html