方法是與特定類型關(guān)聯(lián)的函數(shù)。在類、結(jié)構(gòu)體和枚舉中都可以定義方法。方法可以是實(shí)例方法,也可以是類型方法。
## 實(shí)例方法
實(shí)例方法是屬于某一特定類、結(jié)構(gòu)體或枚舉的函數(shù)。它們提供訪問和修改實(shí)例屬性的方法,或者提供與實(shí)例相關(guān)的功能。實(shí)例方法和函數(shù)的功能相同,具有完全相同的語法。
在實(shí)例方法的大括號內(nèi),可以訪問局部變量和全局變量。實(shí)例方法同樣也可以調(diào)用其他實(shí)例方法。
### 局部變量和全局變量
~~~
class Counter {
var count: Int = 0
func incrementBy(amount: Int, numberOfTimes: Int) {
count += amount * numberOfTimes
}
}
let counter = Counter()
counter.incrementBy(5, numberOfTimes: 3)
print("\(counter.count)") // 15
~~~
如上所示:類Counter中有一個變量count,和一個實(shí)例方法incrementBy。在incrementBy方法內(nèi)可以訪問全局變量count。
### 修改外部參數(shù)名稱
如上面的例子,在外部調(diào)用方法時使用`incrementBy(5, numberOfTimes: 3)`,如果你覺得這樣太麻煩,我們還可以省略numberOfTimes這個名稱,只需參數(shù)名前加下劃線。即修改方法體為`func incrementBy(amount: Int, _ numberOfTimes: Int)`,此時的外部訪問變?yōu)閌counter.incrementBy(5, 3)`。
### Self屬性
在Swift中也可以使用self訪問全局屬性或全局方法。
~~~
struct Point {
var x = 0.0, y = 0.0
func isToTheRightOfX(x: Double) -> Bool {
// 這里有內(nèi)部和外部屬性
return self.x > x
}
}
let somePoint = Point(x: 4.0, y: 5.0)
print("\(somePoint.isToTheRightOfX(1.0))") // true
~~~
### 在實(shí)例方法中修改值類型
在swift中,不但可以給類添加方法,還可以在結(jié)構(gòu)體和枚舉中添加方法。
~~~
struct Point {
var x = 0.0, y = 0.0
mutating func moveByX(deltaX: Double, y deltaY: Double) {
x += deltaX
y += deltaY
}
}
var somePoint = Point(x: 1.0, y: 1.0)
somePoint.moveByX(2.0, y: 3.0)
print("(\(somePoint.x), \(somePoint.y))") // (3.0, 4.0)
let fixedPoint = Point(x: 3.0, y: 3.0)
// 結(jié)構(gòu)體是值對象,使用let常量后,無法修改內(nèi)部值
fixedPoint.moveByX(2.0, y: 3.0) // 拋錯
~~~
由于結(jié)構(gòu)體和枚舉是值類型,默認(rèn)情況下,實(shí)例方法中是不可以修改值類型的屬性。我們只可以在外部修改值類型中的屬性。如果你想在實(shí)例中修改值類型的屬性,只需在方法名前加mutating關(guān)鍵字。
### 在實(shí)例方法中修改結(jié)構(gòu)體或枚舉
在結(jié)構(gòu)體和枚舉內(nèi),self代表當(dāng)前結(jié)構(gòu)體或枚舉,我們還可以通過mutating修改當(dāng)前結(jié)構(gòu)體或枚舉。
~~~
// 結(jié)構(gòu)體測試
struct Point {
var x = 0.0, y = 0.0
mutating func moveByX(deltaX: Double, y deltaY: Double) {
self = Point(x: x + deltaX, y: y + deltaY)
}
}
// 枚舉測試
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
print("\(ovenLight.next())") // High
print("\(ovenLight.next())") // Off
~~~
如上所示,在實(shí)例方法中就可修改self。
## 類型方法
在方法中我們可以不初始化類就調(diào)用類的內(nèi)部方法,這就是類型方法。
~~~
class SomeClass {
class func someTypeMethod() {
// type method implementation goes here
}
}
SomeClass.someTypeMethod()
~~~
如上,我們只需在方法名前添加class關(guān)鍵字,就可直接使用類名加方法名調(diào)用someTypeMethod方法。
接下來為大家演示怎么直接使用結(jié)構(gòu)體名加方法名。使用到的關(guān)鍵字為static
~~~
// 結(jié)構(gòu)體
struct LevelTracker {
// static修改屬性,方法體要修改static屬性,方法前要使用static
static var highestUnlockedLevel = 1
static func levelIsUnlocked(level: Int) -> Bool {
return level <= highestUnlockedLevel
}
}
print("\(LevelTracker.levelIsUnlocked(2))") // false
~~~
## 其他
### 參考資料
[The Swift Programming Language (Swift 2.1)](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html)
### 文檔修改記錄
| 時間 | 描述 |
|-----|-----|
| 2015-10-30 | 根據(jù) [The Swift Programming Language (Swift 2.1)](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html)中的中的Methods總結(jié) |
版權(quán)所有:[http://blog.csdn.net/y550918116j](http://blog.csdn.net/y550918116j)
- 前言
- Swift函數(shù)
- Swift閉包(Closures)
- Swift枚舉(Enumerations)
- Swift類和結(jié)構(gòu)體(Classes and Structures)
- Swift屬性(Properties)
- Swift方法(Methods)
- Swift下標(biāo)(Subscripts)
- Swift繼承(Inheritance)
- Swift初始化(Initialization)
- Swift銷毀(Deinitialization)
- Swift可選鏈(Optional Chaining)
- Swift錯誤處理(Error Handling)
- Swift類型選擇(Type Casting)
- Swift協(xié)議(Protocols)
- Swift訪問控制(Access Control)
- Swift高級運(yùn)算符(Advanced Operators)
