Swift教程之方法

方法

方法是與特定類型相關聯的函數。類、結構體和枚舉都可以定義實例方法,這些方法封裝了特定任務和功能來處理給定類型的實例,也可以定義與類型本身相關聯的類型方法(類似于Objective-C中的類方法)。

<br />

實例方法

實例方法是屬于特定類、結構體或枚舉的實例的函數。通過提供訪問和修改實例屬性的方法,或通過提供與實例的目的相關的功能來支持這些實例的函數,實例方法與函數具有完全相同的語法。

實例方法具有對該類型的所有其他實例方法和屬性的隱式訪問,且只能在其所屬類型的特定實例上調用實例方法,若沒有現有的實例,則不能被單獨調用。

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

let counter = Counter()
// the initial counter value is 0
counter.increment()
// the counter's value is now 1
counter.increment(by: 5)
// the counter's value is now 6
counter.reset()
// the counter's value is now 0

self屬性

類型的實例都有一個self的隱式屬性,它與實例本身完全相同。

上述increment()方法修改如下:

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

在代碼中不需要顯示書寫self,Swift會假定在使用當前屬性或方法名稱時指向當前實例的屬性或方法。

當實例方法的參數名與該實例的屬性名相同時,有必要使用self屬性來區分參數名和屬性名。

struct Point {
    var x = 0.0, y = 0.0
    func isToTheRightOf(x: Double) -> Bool {
        return self.x > x
    }
}
let somePoint = Point(x: 4.0, y: 5.0)
if somePoint.isToTheRightOf(x: 1.0) {
    print("This point is to the right of the line where x == 1.0")
}
// Prints "This point is to the right of the line where x == 1.0"

若沒有書寫self前綴,Swift會假設兩個x都是x的方法參數。

在實例方法中修改值類型

由于結構體和枚舉是值類型,默認情況下,不能從其實例方法修改值類型的屬性。

使用mutating修飾符可以修改特定方法的結構體或枚舉的屬性,mutating關鍵字放在func關鍵字之前:

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)
print("The point is now at (\(somePoint.x), \(somePoint.y))")
// Prints "The point is now at (3.0, 4.0)"

不能在結構體類型常量上調用mutating方法,因為其屬性不能更改。

let fixedPoint = Point(x: 3.0, y: 3.0)
fixedPoint.moveBy(x: 2.0, y: 3.0)
// this will report an error

在mutating方法中分配self

mutating方法可以為隱式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)
    }
}

枚舉的mutating方法可以將隱式self屬性設置為與同一枚舉不同的情況:

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 is now equal to .high
ovenLight.next()
// ovenLight is now equal to .off

<br />

類型方法

類型方法是定義在類型本身上調用的方法。通過在方法的func關鍵字前編寫static關鍵字來指示類型方法,也可以使用class關鍵字允許子類重寫超類的該方法的實現。

在類型上使用點語法調用類型方法,而不是該類型的實例:

class SomeClass {
    class func someTypeMethod() {
        // type method implementation goes here
    }
}
SomeClass.someTypeMethod()

在類型方法體內,隱式self屬性指類型本身,而不是該類型的實例,可以使用self來消除類型屬性和類型方法參數之間的歧義。

struct LevelTracker {
    static var highestUnlockedLevel = 1
    var currentLevel = 1
    
    static func unlock(_ level: Int) {
        if level > highestUnlockedLevel { 
        highestUnlockedLevel = level 
        }
    }
    
    static func isUnlocked(_ level: Int) -> Bool {
        return level <= highestUnlockedLevel
    }
    
    @discardableResult
    mutating func advance(to level: Int) -> Bool {
        if LevelTracker.isUnlocked(level) {
            currentLevel = level
            return true
        } else {
            return false
        }
    }
}

class Player {
    var tracker = LevelTracker()
    let playerName: String
    func complete(level: Int) {
        LevelTracker.unlock(level + 1)
        tracker.advance(to: level + 1)
    }
    init(name: String) {
        playerName = name
    }
}

var player = Player(name: "Argyrios")
player.complete(level: 1)
print("highest unlocked level is now \(LevelTracker.highestUnlockedLevel)")
// Prints "highest unlocked level is now 2"

player = Player(name: "Beto")
if player.tracker.advance(to: 6) {
    print("player is now on level 6")
} else {
    print("level 6 has not yet been unlocked")
}
// Prints "level 6 has not yet been unlocked"
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容