Swift for iOS Development (10)-Method

version

Xcode 11.3.1
Swift 5.1.3

method

Methods are functions associated with certain types.
Instance methods encapsulate specific tasks and functions for instances of a given type; type methods are associated with the type itself. Type methods are similar to class methods in Objective-C.

  • In Objective-C, a class is the only type that can define methods.
  • In Swift, you can define methods on types (classes/structures/enums).

Instance method

An instance method is a method belonging to an instance of a particular class, structure, or enumeration type.
The instance method has the following characteristics:

  • Can access and modify instance properties
  • Can access other instance methods of its type
  • It should be written between the front and back braces (()) of the type it belongs to
  • Can only be called by a specific instance of the class it belongs to
class Counter {
    
    
    
    var count = 0
    
    func increment() {
    
    
        count += 1
        printSelf()
    }
    
    func increment(by amount: Int) {
    
    
        count += amount
        printSelf()
    }
    
    func reset() {
    
    
        count = 0
        printSelf()
    }
    
    func printSelf() {
    
    
        print("count = \(count)")
    }
}

let counter = Counter()
counter.increment()
counter.increment(by: 2)
counter.reset()

/**
 count = 1
 count = 3
 count = 0
 */

In the above example, implicit calls are used to access properties/methods.

self attribute

Each instance of the type has an implicit attribute called self, which is completely equivalent to the instance itself. You can use this implicit self attribute in the instance method of an instance to refer to the current instance. The
reason why it is said in the above example is The implicit call is because it uses the implicit self attribute. The
full wording (explicit call) is:

func increment() {
    
    
        self.count += 1
        self.printSelf()
}

Although we can abbreviate self, we still need to use explicit writing in some cases.
For example, in the above example, if the amount in the method increment(by amount: Int) is changed to count, then the result is not what we want. Because the parameter count priority is greater than the storage attribute count, and we want to calculate the storage attribute count.
Then you need to use self, and the effect is the same:

func increment(by count: Int) {
    
    
        self.count += count
        printSelf()
}

External parameter name and local parameter name

In the previous function chapters, we have discussed parameter labels and parameter names.
In this chapter, because it involves method calls, we will change the parameter labels to external parameter names, and the parameter names to local parameter names.
Swift function parameters There can be a local name (used inside the function body) and an external name (used when calling the function) at the same time.
Like in Objective-C, the name of a method in Swift usually uses a preposition to point to the first parameter of the method, such as with, for, by, etc.

In the first example, by is the name of the external parameter, and amount is the name of the local parameter

func increment(by amount: Int) {
    
    
        count += amount
        printSelf()
}

counter.increment(by: 2)

We can also use the underscore "_" to replace the external parameter name, so that there is no external parameter name (parameter label) when calling the method:

func increment(_ count: Int) {
    
    
        self.count += count
        printSelf()
}

counter.increment(2)

Modify the value type in the instance method

Structures and enumerations in Swift language are value types. Under normal circumstances, the attribute of the value type cannot be modified in its instance method.
E.g:

struct Size {
    
    
    
    var width = 10
    var height = 20

    // 以下方法报错
    func increment(by amount: Int) {
    
    
        width += amount;
        height += amount;
    }
}

However, if you really need to modify the properties of a structure or enumeration in a specific method, you can choose to mutate this method, and then the method can change its properties from within the method; the method can also give it hidden The contained self attribute gives a brand new instance, which will replace the existing instance at the end of the method.
E.g:

struct Size {
    
    
    
    var width = 10
    var height = 20
    
    mutating func increment(by amount: Int) {
    
    
        width += amount;
        height += amount;
    }
}

var size = Size()
print("\(size)")
// Size(width: 10, height: 20)

size.increment(by: 5)
print("\(size)")
// Size(width: 15, height: 25)

Assign a value to self in a mutable method

In the above example, it can be rewritten as follows, and the result is the same:

struct Size {
    
    
    
    var width = 10
    var height = 20
    
    mutating func increment(by amount: Int) {
    
    
//        width += amount;
//        height += amount;
        self = Size(width: width+amount, height: height+amount)
    }
}

The variable method of enumeration can set self to different members of the same enumeration type:

enum TriStateSwitch {
    
    
    case off, low, high
    mutating func next() {
    
    
        switch self {
    
    
        case .off:
            self = .low
        case .low:
            self = .high
        case .high:
            self = .off
        }
    }
}
var ovenLight = TriStateSwitch.low
ovenLight.next()
// ovenLight 现在等于 .high
ovenLight.next()
// ovenLight 现在等于 .off

Type method

An instance method is called by an instance of a certain type.
Type methods are called by the type itself.
To declare the type method of structure and enumeration, add the keyword static before the func keyword of the method.
The class may use the keyword class to allow subclasses to override the implementation method of the parent class.

class Math {
    
    
    class func abs(number: Int) -> Int {
    
    
        if number < 0 {
    
    
            return (-number)
        }else {
    
    
            return number
        }
    }
}

struct Sample {
    
    
    static func abs(number: Int) -> Int {
    
    
        if number < 0 {
    
    
            return (-number)
        }else {
    
    
            return number
        }
    }
}

let number1 = Math.abs(number: -5)
let number2 = Sample.abs(number: -10)

print(number1)
print(number2)
/**
 5
 10
 */

Guess you like

Origin blog.csdn.net/u012078168/article/details/104494695