Methods in Swift

Swift supports methods defined on struct types.

import Foundation

struct Rect {
    var width: Int
    var height: Int
    
    // This `area` method is defined on the `Rect` struct.
    func area() -> Int {
        return width * height
    }
    
    // Methods can be defined for either value or mutating types.
    // Here's an example of a non-mutating method.
    func perim() -> Int {
        return 2 * width + 2 * height
    }
}

func main() {
    var r = Rect(width: 10, height: 5)
    
    // Here we call the 2 methods defined for our struct.
    print("area: ", r.area())
    print("perim:", r.perim())
    
    // Swift automatically handles the distinction between value and
    // reference types for method calls. You may want to use a `mutating`
    // method if you need to change the struct's properties.
    let rp = r
    print("area: ", rp.area())
    print("perim:", rp.perim())
}

main()

To run the program, save it as a .swift file and use the Swift compiler:

$ swift methods.swift
area:  50
perim: 30
area:  50
perim: 30

In Swift, structs are value types, and their methods are non-mutating by default. If you need to modify the struct’s properties within a method, you should mark it as mutating.

Swift doesn’t have a direct equivalent to Go’s pointer receivers, as it handles value and reference semantics differently. Instead, you can use class for reference semantics or mutating methods on structs for value semantics with modification.

Next, we’ll look at Swift’s mechanism for grouping and naming related sets of methods: protocols, which are similar to interfaces in other languages.