methods

Enumerations, structs, and classes can all define instance methods and type methods.

  • Instance Method: called from the Instance object.
  • Type Method: called by Type, usingstaticorclassKeyword definition.

self

  • In the instance method,selfRepresents the current instance.
  • In the type method,selfRepresents the current type.
/ / method
class Car {
    static var count = 0
    init(a) {
        Car.count + = 1
    }
    static func getCount(a) -> Int  {
        count   // Reachable}}let c0 = Car(a);let c1 = Car(a);print(Car.getCount())
Copy the code

In static func getCount, count is equivalent to self.count, Car. Self. count, Car

mutating

Structs and enumerations are value types, and by default, members of value types cannot be modified by their own instance methods.

  • Before the func keywordmutatingThis modification behavior can be allowed.
struct Point {
    var x = 0.0, y = 0.0
    mutating func moveBy(deltaX: Double.deltaY: Double) {
        x + = deltaX
        y + = deltaY
    }
}

enum StateSwitch {
    case low, middel, high
    mutating func next(a) {
        switch self {
        case .low:
            self = .middel
        case .middel:
            self = .high
        case .high:
            self = .low
        }
    }
}
Copy the code

@discardableResult

Add @discardableresult before func to eliminate the warning that the return value after a function call is not used.

struct Point {
    var x = 0.0, y = 0.0
    @discardableResult mutating func moveBy(deltaX: Double.deltaY: Double) -> Int {
        x + = deltaX
        y + = deltaY
        return 10}}var p = Point()
p.moveBy(deltaX: 1, deltaY: 10)
Copy the code