TExcelTAD
Home › Swift › Swift Methods

Swift Methods

A method is a function that belongs to a type. Instance methods work on one particular value (cart.add(item)), while type methods belong to the type as a whole (Temperature.fromFahrenheit(98.6)). Structs, classes and enums can all have both.

Instance methods

An instance method is written inside the type's braces and can use the instance's properties directly. The implicit self refers to the current instance; you only need to write it when a parameter has the same name as a property.

swift · try it yourself
struct ShoppingCart {
    var items: [String] = []
    var total = 0.0

    mutating func add(_ name: String, price: Double) {
        items.append(name)
        total += price
    }

    func receipt() -> String {
        "\(items.count) items: \(items.joined(separator: ", ")) – total $\(total)"
    }
}

var cart = ShoppingCart()
cart.add("Bread", price: 2.25)
cart.add("Milk", price: 1.5)
print(cart.receipt())
2 items: Bread, Milk – total $3.75

Method parameters follow the same rules as functions: argument labels, _ to omit a label, and default values all work.

mutating methods in value types

Structs and enums are value types, so a method that changes stored properties must be marked mutating. Enums often use this to move between cases:

swift · try it yourself
enum Light {
    case off, low, high

    mutating func next() {
        switch self {
        case .off:  self = .low
        case .low:  self = .high
        case .high: self = .off
        }
    }
}

var lamp = Light.off
for _ in 1...4 {
    lamp.next()
    print(lamp)
}
low
high
off
low

You can only call a mutating method on a variable (var), never on a let constant. Classes don't use mutating at all because they are reference types.

Type methods with static

A type method is called on the type itself. A common use is a factory method that creates instances in a convenient way. (import Foundation is only needed here for String(format:).)

swift · try it yourself
import Foundation

struct Temperature {
    var celsius: Double

    static func fromFahrenheit(_ f: Double) -> Temperature {
        Temperature(celsius: (f - 32) * 5 / 9)
    }

    static let freezing = Temperature(celsius: 0)

    func isWarmer(than other: Temperature) -> Bool {
        celsius > other.celsius
    }
}

let body = Temperature.fromFahrenheit(98.6)
print(String(format: "%.1f °C", body.celsius))
print(body.isWarmer(than: .freezing))
37.0 °C
true

In a class, you can write class func instead of static func to let subclasses override the type method.

Methods returning Self for chaining

Returning a modified copy lets callers chain calls in a fluent style — common for configuration values:

swift · try it yourself
struct Greeting {
    var text = "Hello"
    var excited = false

    func to(_ name: String) -> Greeting {
        var copy = self
        copy.text += ", \(name)"
        return copy
    }

    func loud() -> Greeting {
        var copy = self
        copy.excited = true
        return copy
    }

    func render() -> String { excited ? text.uppercased() + "!" : text + "." }
}

print(Greeting().to("Minh").render())
print(Greeting().to("Minh").loud().render())
Hello, Minh.
HELLO, MINH!

The original value is never touched — each method returns a new one. SwiftUI's modifiers (.padding().background(...)) work on the very same idea.

Summary

Method kind Declared with Called on Can change properties?
Instance (class) func an instance Yes
Instance (struct/enum) func an instance No
Mutating (struct/enum) mutating func a var instance Yes
Type method static func the type Only static properties
Overridable type method class func the class Only static/class properties

Tip: Use argument labels to make call sites read like English: a.isWarmer(than: b) is clearer than a.isWarmer(b).

Test yourself

Why must next() in an enum be marked mutating?

  1. Because it returns a value
  2. Because it assigns a new value to self
  3. Because enums cannot have methods otherwise
  4. It does not need it

How do you call a type method fromFahrenheit of Temperature?

  1. Temperature.fromFahrenheit(50)
  2. Temperature().fromFahrenheit(50)
  3. fromFahrenheit(Temperature, 50)
  4. static.fromFahrenheit(50)

Which keyword lets a subclass override a type method?

  1. static func
  2. class func
  3. final func
  4. mutating func