Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 146 ยท Structures, Classes and Enums

Methods

Learn Swift methods - instance methods, self, mutating methods on structs, type methods with static and class, method chaining, and the compiler errors that teach the rules.

A method is a function that lives inside a type. Where a free function like max(a, b) works on whatever you hand it, a method works on an instance of its type and can read and change that instance's properties. array.append(3), string.uppercased() and date.addingTimeInterval(60) are all methods.

Swift lets structs, classes and enums all have methods, which is unusual among languages (many only allow them on classes). The price is one extra keyword, mutating, that you will meet in this lesson and that explains one of the most common beginner errors. Then we cover methods that belong to the type itself, self, chaining, and how to choose between a method and a computed property.

Instance methods

An instance method is declared inside the type and called on an instance with dot syntax. Inside it, you can use the type's properties by name.

Swift A first instance method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Inside describe(), the call area() has no room. in front. It does not need one: the method is already running on one particular instance, and Swift looks the name up on that instance automatically.

Parameters work as in any function, including argument labels, defaults and inout. See Functions and Argument Labels if you want a refresher.

self

Every instance method has an implicit constant called self that refers to the instance it is running on. You rarely have to type it, but you must in two situations. The first is when a parameter has the same name as a property:

Swift self resolves a name clash

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The second situation is inside an escaping closure in a class, where Swift insists you write self. so you notice that the closure keeps the object alive. That is covered in Memory Management with ARC and Escaping Closures.

Do not litter your code with self.. Use it where it removes ambiguity and leave it out elsewhere; the compiler will tell you when it is required.

Mutating methods

Here is the rule that surprises people. Structs and enums are value types, and by default a method on a value type is not allowed to change the instance's properties. To allow it, you mark the method mutating.

Swift Forgetting mutating (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler reports left side of mutating operator isn't mutable: 'self' is immutable and adds the note mark method 'mutating' to make 'self' mutable. Plain assignments such as self.count = 0 give the sibling message cannot assign to property: 'self' is immutable. Adding the keyword fixes it:

Swift mutating makes it work

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

What does mutating really mean? Conceptually, a mutating method receives self as an inout parameter: it gets the instance, may change it, and hands it back. That is why a mutating method can even assign a brand new value to self.

Two consequences follow:

  • You can only call a mutating method on a variable. On a let constant the compiler says cannot use mutating member on immutable value: 'counter' is a 'let' constant.
  • Classes never need mutating. A class instance is shared by reference, so a method can always change its stored properties.

Mutating in enums

Enums can reassign self to switch between cases, which makes them natural state machines.

Swift An enum that changes itself

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Return a new value instead

Many Swift APIs come in pairs: a mutating method named like a verb and a non-mutating one named like a noun or past participle. sort() changes the array, sorted() returns a new one. You can follow the same pattern.

Swift Mutating and non-mutating pairs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The non-mutating version works on let values, is easy to reason about, and costs very little, because small structs copy cheaply.

Type methods

An instance method needs an instance. Sometimes the behavior belongs to the type as a whole, such as a factory or a helper that needs no stored state. Declare these with static, and call them on the type name.

Swift static methods and factories

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Inside a type method, self means the type, not an instance, so you can call other type methods without the type name, but you cannot touch instance properties. Classes add class func, which subclasses may override, while static means final. See Inheritance.

Method chaining

When a method returns an instance (or self in a class), you can call another method on the result. This style, often called a fluent interface, makes configuration code read like a sentence.

Swift Chaining non-mutating methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Mutating methods cannot be chained this way, because they return Void. Choose the non-mutating style when chaining matters.

Methods or computed properties?

Both can hide a calculation. A rough guide:

  • A property answers a question about what the thing is: cheap, no side effects, no arguments. rectangle.area, text.count.
  • A method does something, takes arguments, may be expensive or have side effects. rectangle.scaled(by: 2), array.sort().

If calling it twice might give different results, or it takes visible time, make it a method. See Properties for the other half.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the compiler report when a struct method does count += 1 but is not marked mutating?

    In a value type, self is immutable inside normal methods. Marking the method mutating allows changes to its properties.
  2. 2. On which kind of instance can you call a mutating method?

    Mutating methods change the value in place, so the instance must live in a mutable place such as a var.
  3. 3. Which keyword declares a method called on the type itself, such as Money.dollars(5)?

    static func declares a type method. In classes, class func does the same but can be overridden.
  4. 4. Why do classes not need the mutating keyword?

    A class variable stores a reference. Changing a property modifies the shared object, not the reference itself.
  5. 5. When is a method a better choice than a computed property?

    Properties should feel like cheap values. Work with inputs, side effects or cost reads better as a method.

Summary

  • Methods are functions inside a type; they work on self, usually implicitly.
  • Write self. only to resolve name clashes and where the compiler requires it, for example in escaping closures.
  • Methods on structs and enums that change properties or reassign self must be mutating, and need a var instance.
  • Classes do not use mutating.
  • static func (or class func for overridable ones) declares type methods and factories.
  • Offer a non-mutating, value-returning twin (sorted() next to sort()) when chaining is useful.
  • Properties answer cheap questions; methods do work.

Next: Initializers