Swift4 基礎(chǔ)部分: Methods

本文是學(xué)習(xí)《The Swift Programming Language》整理的相關(guān)隨筆,基本的語法不作介紹,主要介紹Swift中的一些特性或者與OC差異點。

系列文章:

實例方法(Instance Methods)

實例方法我們直接看例子:

class Counter {
    var count = 0;
    func increment(){
        count += 1;
    }
    
    func increment(by amount: Int){
        count += amount;
    }
    
    func reset(){
        count = 0;
    }
}

let counter = Counter();
counter.increment();
print("count:\(counter.count)");
counter.increment(by: 2);
print("count:\(counter.count)");
counter.reset();
print("count:\(counter.count)");

執(zhí)行結(jié)果:

count:1
count:3
count:0

self屬性(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.
  • 每一個實例都有一個隱含屬性叫做self,self完全等同于該實例本身。你可以在一個實例的實例方法中使用這個隱含的self屬性來引用當(dāng)前實例。

針對上述例子做改造,得到的結(jié)果完全一致。

class Counter {
    var count = 0;
    func increment(){
        self.count += 1;
    }
    
    func increment(by amount: Int){
        self.count += amount;
    }
    
    func reset(){
        self.count = 0;
    }
}

let counter = Counter();
counter.increment();
print("count:\(counter.count)");
counter.increment(by: 2);
print("count:\(counter.count)");
counter.reset();
print("count:\(counter.count)");

函數(shù)中修改值類型數(shù)據(jù)(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. 
  • 結(jié)構(gòu)體與枚舉都是值類型的數(shù)據(jù),他們內(nèi)部的屬性值不能通過實例方法更改。
However, if you need to modify the properties of your structure or 
enumeration within a particular method, you can opt in to mutating 
behavior for that method. The method can then mutate (that is, change) its 
properties from within the method, and any changes that it makes are 
written back to the original structure when the method ends. 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. 
  • 如果你確實需要在某個特定方法中修改結(jié)構(gòu)體或者枚舉的屬性,你可以選擇變異(mutating)這個方法,可以通過該方法就可以從方法內(nèi)部改變它的屬性;并且它做的任何改變在方法結(jié)束時還會保留在原始結(jié)構(gòu)中。方法還可以給它隱含的self屬性賦值一個全新的實例,這個新實例在方法結(jié)束后將替換原來的實例。

例子:

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();
somePoint.moveBy(x: 1.0, y: 1.0);
print("The point is now at (\(somePoint.x), \(somePoint.y))");

執(zhí)行結(jié)果:

The point is now at (1.0, 1.0)

在變異方法中給self賦值(Assigning to self Within a Mutating Method)

Mutating methods can assign an entirely new instance to the implicit self property. 
  • 變異方法能夠賦給隱含屬性self一個全新的實例。

例子:

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);
    }
}

var somePoint = Point();
somePoint.moveBy(x: 1.0, y: 1.0);
print("The point is now at (\(somePoint.x), \(somePoint.y))");

執(zhí)行結(jié)果:

The point is now at (1.0, 1.0)
Mutating methods for enumerations can set the implicit self parameter to be a different case from the same enumeration:
  • 枚舉的變異方法可以把self設(shè)置為相同的枚舉類型中不同的成員.

例子:

enum TriDateSwitch{
    case off, low, high
    mutating func next() {
        switch self {
        case .off:
            self = .low;
        case .low:
            self = .high;
        case .high:
            self = .off;
            
        }
    }
}

var ovenLight = TriDateSwitch.low;
print("ovenLight:\(ovenLight)");
ovenLight.next();
print("ovenLight:\(ovenLight)");
ovenLight.next();
print("ovenLight:\(ovenLight)");

執(zhí)行結(jié)果:

ovenLight:low
ovenLight:high
ovenLight:off

類方法(Type Methods)

You can also define methods that are called on the type itself. These 
kinds of methods are called type methods. You 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.
  • 你也可以定義類型本身調(diào)用的方法,這種方法就叫做類型方法。聲明類的類型方法,在方法的func關(guān)鍵字之前加上關(guān)鍵字class;聲明結(jié)構(gòu)體和枚舉的類型方法,在方法的func關(guān)鍵字之前加上關(guān)鍵字static。

自己寫一個計算器的例子:

class Calculator {
    class func add(_ firstNum:Double,_ secondNum:Double) -> Double{
        return firstNum + secondNum;
    }
    
    class func minus(_ firstNum:Double,_ secondNum:Double) -> Double{
        return firstNum - secondNum;
    }
    
    class func multiplied(by firstNum:Double,_ secondNum:Double) -> Double{
        return firstNum * secondNum;
    }
    
    class func divided(by firstNum:Double,_ secondNum:Double) -> Double{
        return firstNum / secondNum;
    }
}

print("Add : \(Calculator.add(1.0,2.0))");
print("Minus : \(Calculator.minus(1.0,2.0))");
print("Multiplied : \(Calculator.multiplied(by:1.0,2.0))");
print("Divided : \(Calculator.divided(by:1.0,2.0))");

執(zhí)行結(jié)果:

Add : 3.0
Minus : -1.0
Multiplied : 2.0
Divided : 0.5

上述的類改為結(jié)構(gòu)體實現(xiàn):

struct Calculator{
    static func add(_ firstNum:Double,_ secondNum:Double) -> Double{
        return firstNum + secondNum;
    }
    
    static func minus(_ firstNum:Double,_ secondNum:Double) -> Double{
        return firstNum - secondNum;
    }
    
    static func multiplied(by firstNum:Double,_ secondNum:Double) -> Double{
        return firstNum * secondNum;
    }
    
    static func divided(by firstNum:Double,_ secondNum:Double) -> Double{
        return firstNum / secondNum;
    }
}

print("Add : \(Calculator.add(1.0,2.0))");
print("Minus : \(Calculator.minus(1.0,2.0))");
print("Multiplied : \(Calculator.multiplied(by:1.0,2.0))");
print("Divided : \(Calculator.divided(by:1.0,2.0))");

執(zhí)行結(jié)果:

Add : 3.0
Minus : -1.0
Multiplied : 2.0
Divided : 0.5
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容