免费开源的iOS开发学习平台

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()//打印:count:11

counter.reset()
counter.toString()//打印:count: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()//打印:Point(5,5)

p.moveBy(deltax: 10, deltay: 10)
p.toString()//打印:Point(15,15)

p.changeBy(deltax: 20, deltay: 20)
p.toString()//打印:Point(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() //打印:east
dir.switcher()
dir.toString() //打印:west
dir.switcher()
dir.switcher()
dir.toString() //打印:south

类型方法

声明类的类型方法,在方法的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