DEV Community

Naveen Ragul B
Naveen Ragul B

Posted on • Updated on

Swift - Methods

Methods are functions that are associated with a particular type. Classes, structures, and enumerations can all define :

  1. Instance methods
  2. Type methods.

Type methods by writing the static keyword before the method’s func keyword. Classes can use the class keyword instead, to allow subclasses to override the superclass’s implementation of that method.

  • The self Property :
    For instance, it is exactly equivalent to the instance itself.
    For Type property, it refers to the type itself.

  • To modify the properties of your structure or enumeration within a particular method, you can opt in to mutating behavior for that method. It cannot be modified by default from a method. because structures and enumerations are value types.

  • Swift structs are immutable objects, calling a mutating function actually returns a new struct in-place

example :

struct Point {
    var x = 0.0, y = 0.0
    mutating func moveBy(x deltaX: Double, y deltaY: Double) {
        x += deltaX
        y += deltaY
    }
}
var somePoint = Point(x: 1.0, y: 1.0)
somePoint.moveBy(x: 2.0, y: 3.0)
Enter fullscreen mode Exit fullscreen mode
  • Mutating methods can assign an entirely new instance to the implicit self property.

example 1:

struct Point {
    var x = 0.0, y = 0.0
    mutating func moveBy(x deltaX: Double, y deltaY: Double) {
        self = Point(x: x + deltaX, y: y + deltaY)
    }
}
Enter fullscreen mode Exit fullscreen mode

example 2:

enum TriStateSwitch {
    case off, low, high
    mutating func next() {
        switch self {
        case .off:
            self = .low
        case .low:
            self = .high
        case .high:
            self = .off
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)