Swiftly

Swift 5.7 references for busy coders

Methods

Methods are functions that belong to a struct, class, or enum.

Instance methods

Instance methods belong to an instance of a struct, class, or enum. They may access the instance’s variables. Below are examples of an instance method intro():

Struct example

struct Person {
  let name: String

  init(name: String) {
    self.name = name
  }

  func intro() {
    print("I'm \(name).")
  }
}

let amy = Person(name: "Amy")
amy.intro() // I'm Amy.

Class example

class Person {
  let name: String

  init(name: String) {
    self.name = name
  }

  func intro() {
    print("I'm \(name).")
  }
}

let amy = Person(name: "Amy")
amy.intro() // I'm Amy.

Enum example

enum Beatle: String {
  case john
  case paul
  case george
  case ringo

  func intro() {
    print("I'm \(rawValue).")
  }
}

let john = Beatle.john
john.intro() // I'm john.

Mutating instance methods

Because structs are value types, an instance method that modifies its instance must be marked as mutating:

struct Player {
  var name: String
  var level: Int

  mutating func levelUp() {
    level += 1
  }
}

var player = Player(name: "Amy", level: 1)
player.levelUp()
print(player.level) // 2

Static/class methods

Static and class methods (also known as type methods) belong to a struct/class type itself, rather than an instance of a struct/class. They are declared with static for a struct or class for a class:

struct Person {
  let name: String

  init(name: String) {
    self.name = name
  }

  static func intro() {
    print("I'm a static method.")
  }
}

Person.intro() // I'm a static method.
class Person {
  let name: String

  init(name: String) {
    self.name = name
  }

  class func intro() {
    print("I'm a class method.")
  }
}

Person.intro() // I'm a class method.

Further reading