Methods
The fact that structures and enumerations can define methods in Swift is a major difference from C and Objective-C.
Instance Methods
Instance methods are functions that belong to instances of a particular class, structure, or enumeration.
1 | class Counter { |
The self Property
- Every instance of a type has an implicit property called self, which is exactly equivalent to the instance itself. You use the self property to refer to the current instance within its own instance methods.
Swift Inferred
Swift assumes that you are referring to a property or method of the current instance
1 | class Counter { |
When to use self
You use the self property to distinguish between the parameter name and the property name.
1 | func increment() { |
Modifying Value Types from Within Instance Methods
- Structures and enumerations are value types. By default, the properties of a value type cannot be modified from within its instance methods.
mutating
keyword means the method can change its properties.- Note that you cannot call a mutating method on a constant of structure type, because its properties cannot be changed, even if they are variable properties,
1 | struct Point { |
Assigning to self Within a Mutating Method
The method can also assign a completely new instance to its implicit self property, and this new instance will replace the existing one when the method ends.
self for structure
1 | struct Point { |
self for Enum
1 | enum TriStateSwitch { |
Type Methods
1 | class SomeClass { |
- called on the type itself
- indicate type methods by writing the
static
keyword before the method’s func keyword. Classes may also use the class keyword to allow subclasses to override the superclass’s implementation of that method. - In Objective-C, you can define type-level methods only for Objective-C classes. In Swift, you can define type-level methods for all classes, structures, and enumerations. Each type method is explicitly scoped to the type it supports.
- Within the body of a type method, the implicit self property refers to the type itself, rather than an instance of that type. This means that you can use self to disambiguate between type properties and type method parameters, just as you do for instance properties and instance method parameters.
1 | struct LevelTracker { |