方法是關(guān)聯(lián)了特定類型的函數(shù)衩婚,用來封裝特定的任務(wù)和功能。Swift中的類效斑,結(jié)構(gòu)體和枚舉都可以定義方法谅猾。
1. 實(shí)例方法
實(shí)例方法 是屬于特定類實(shí)例、結(jié)構(gòu)體實(shí)例或者枚舉實(shí)例的函數(shù)鳍悠。
- 要寫一個(gè)實(shí)例方法,需要把它放在對應(yīng)類的花括號之間
- 實(shí)例方法默認(rèn)可以訪問同類下所有其他實(shí)例方法和屬性
- 實(shí)例方法只能在類型的具體實(shí)例里被調(diào)用坐搔,不能在獨(dú)立于實(shí)例而被調(diào)用
舉個(gè)栗子:
class Counter {
var count = 0
func increment() { // 實(shí)例方法 1
count += 1
}
func increment(by amount: Int) { // 實(shí)例方法 2
count += amount
}
func reset() { // 實(shí)例方法 3
count = 0
}
}
調(diào)用實(shí)例方法藏研,仍然使用點(diǎn)語法:
let counter = Counter()
// 初始化時(shí)count值為 0
counter.increment()
// 現(xiàn)在count值為 1
counter.increment(by: 5)
// 現(xiàn)在count值為 6
counter.reset()
// 現(xiàn)在count值為 0
self 屬性
每一個(gè)類的實(shí)例都隱含一個(gè)叫做self
的屬性,它完全與實(shí)例本身相等概行〈赖玻可以使用self
屬性直接調(diào)用它自身的方法,如上面的increment
方法可以寫成:
func increment() {
self.count += 1
}
如果你沒有顯式地寫出
self
凳忙,Swift默認(rèn)調(diào)用當(dāng)前實(shí)例中的屬性或者方法业踏。但屬性名和實(shí)例方法參數(shù)名相同時(shí),省略self指的是實(shí)例方法參數(shù)涧卵,加上self則指的是屬性勤家。
如:
struct Point {
var x = 0.0, y = 0.0
func isToTheRightOf(x: Double) -> Bool {
return self.x > x // self.x 指的是Point類的屬性 x
// 后面的x值得是函數(shù)isToTheRightOf中的參數(shù) 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")
}
// 結(jié)果為: "This point is to the right of the line where x == 1.0"
在實(shí)例方法中修改值類型
結(jié)構(gòu)體和枚舉是值類型。默認(rèn)情況下柳恐,值類型屬性不能被自身的實(shí)例方法修改伐脖。但是,如果需要在特定的方法中修改結(jié)構(gòu)體或者枚舉的屬性乐设,可以選擇將這個(gè)方法異變(mutating):
struct Point {
var x = 0.0, y = 0.0
// 在func關(guān)鍵字前添加mutating表明這是一個(gè)異變方法
mutating func moveByX(deltaX: Double, y deltaY: Double) {
x += deltaX
y += deltaY
}
}
var somePoint = Point(x: 1.0, y: 1.0) // 注意這里的somePoint必須是變量
somePoint.moveBy(x: 2.0, y: 3.0)
print("The point is now at (\(somePoint.x), \(somePoint.y))")
// 結(jié)果為: "The point is now at (3.0, 4.0)"
注意讼庇,我們不能在常量結(jié)構(gòu)體類型里調(diào)用異變方法,因?yàn)槌A拷Y(jié)構(gòu)人自身屬性不能被改變近尚,即使它們是變量屬性:
let fixedPoint = Point(x: 3.0, y: 3.0)
fixedPoint.moveBy(x: 2.0, y: 3.0)
// 這里將會(huì)報(bào)錯(cuò)
在異變方法里指定自身
異變方法可以指定整個(gè)實(shí)例給隱含的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)
}
}
再舉個(gè)枚舉的栗子:
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 現(xiàn)在為 .high
ovenLight.next()
// ovenLight 現(xiàn)在為 .off
2. 類型方法
在類型本身調(diào)用的方法稱作類型方法。
- 可以通過在
func
關(guān)鍵字之前使用static
關(guān)鍵字來明確一個(gè)類型方法 - 類同樣可以使用
class
關(guān)鍵字來允許子類重寫父類對類型方法的實(shí)現(xiàn)
語法如下:
class SomeClass {
class func someTypeMethod() {
// 方法實(shí)現(xiàn)部分
}
}
// 調(diào)用類型方法
SomeClass.someTypeMethod()
注意: 在類型方法的函數(shù)體中戈锻,隱含的
self
屬性指向了類本身而不是這個(gè)類的實(shí)例歼跟。