Swift:12 方法
方法是與特定類型相關聯的函數。方法包含實例方法和類型方法。與Objectivce-C不同的是,在Swift中類、結構體和枚舉中都可以定義實例方法和類型方法。
實例方法
Swift中類的實例方法用法跟Objective-C類似,如下代碼所示。
class Counter {
var count = 0
func add(){
count += 1
}
func add(by count:Int){
self.count += count
}
func reset(){
count = 0
}
func toString() {
print("count:\(self.count)")
}
}
let counter = Counter()
counter.add()
counter.add(by: 10)
counter.toString()//打?。篶ount:11
counter.reset()
counter.toString()//打?。篶ount:0
由于結構體和枚舉類型是值類型,默認情況值類型的屬性是無法在其實例函數中被修改。不過,可以通過在實例函數前面加上mutating關鍵字來使得該函數能夠修改值類型屬性的值,而且還能通過給self關鍵字賦值來修改整個實例的值。如下代碼所示。
struct Point{
var x = 0
var y = 0
mutating func moveBy(deltax:Int,deltay:Int){
self.x += deltax
self.y += deltay
}
mutating func changeBy(deltax:Int,deltay:Int){
self = Point(x:self.x+deltax,y:self.y+deltay)
}
func toString() {
print("Point(\(self.x),\(self.y))")
}
}
var p = Point(x: 5, y: 5)
p.toString()//打?。篜oint(5,5)
p.moveBy(deltax: 10, deltay: 10)
p.toString()//打?。篜oint(15,15)
p.changeBy(deltax: 20, deltay: 20)
p.toString()//打?。篜oint(35,35)
利用mutating來改變值類型本身這個特性,可以利用枚舉類型的實例函數來切換實例本身的值。
enum director{
case south,east,west,north
mutating func switcher(){
switch self {
case .south:
self = .east
case .east:
self = .west
case .west:
self = .north
case .north:
self = .south
}
}
func toString() {
print(self)
}
}
var dir = director.east
dir.toString() //打?。篹ast
dir.switcher()
dir.toString() //打?。簑est
dir.switcher()
dir.switcher()
dir.toString() //打?。簊outh
類型方法
聲明類的類型方法,在方法的func關鍵詞之前添加關鍵詞class,聲明結構體和枚舉的類型方法,在方法的func關鍵詞之前添加關鍵詞static。下面示例演示如何在結構體中使用類型方法。
struct Score{
static var totalScore = 0
static func resetScore(){
self.totalScore = 0
}
var score = 0
mutating func add(By score:Int) {
self.score += score
Score.totalScore += score
}
}
var score1 = Score()
score1.add(By: 100)
print("score1.score:\(score1.score)")
print("Score.totalScore:\(Score.totalScore)\n")
var score2 = Score()
score2.add(By: 50)
score2.add(By: 90)
print("score2.score:\(score2.score)")
print("Score.totalScore:\(Score.totalScore)\n")
Score.resetScore()
print("Score.totalScore:\(Score.totalScore)")
代碼運行結果如下圖所示。
示例代碼
https://github.com/99ios/23.13