Swift|Swift 方法

实例方法

import UIKit// 实例方法 class Counter { var count = 0 func increment() { count += 1 }func increment(amount: Int) { count += amount }func reset() { count = 0 } }let counter = Counter() counter.increment() print(counter.count) counter.increment(5) print(counter.count) counter.reset() print(counter.count)

console log 如下

Swift|Swift 方法
文章图片
实例方法.png
mutating 关键字的使用
注意:结构体和枚举都是值拷贝,默认不能修改实例值,如果要修改方法前面需要加上 mutating 关键字
// mutating 关键字的使用 struct Point { var x = 0.0, y = 0.0 mutating func moveBy(deltaX: Double, deltaY: Double) { x += deltaX y += deltaY }mutating func moveTwo(deltaX: Double, deltaY: Double) { self = Point(x: x + deltaX, y: y + deltaY) } }var somePoint = Point(x: 1.0, y: 1.0) somePoint.moveBy(2.0, deltaY: 3.0) print("The point is now at (\(somePoint.x), \(somePoint.y))")somePoint.moveTwo(3.0, deltaY: 4.0) print("The point is now at (\(somePoint.x), \(somePoint.y))")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.off ovenLight.next() if ovenLight == TriStateSwitch.low { print("ovenLight now is low") } ovenLight.next() if ovenLight == TriStateSwitch.high { print("ovenLight now is high") }

console log 如下

Swift|Swift 方法
文章图片
mutating 关键字的使用.png
【Swift|Swift 方法】类方法 --用class 关键字声明
// 类方法 class SomeClass { class func someTypeMethod(){ print("SomeClass type method.") } }SomeClass.someTypeMethod()

console log 如下

Swift|Swift 方法
文章图片
类方法.png
实战
// 方法实战 struct LevelTracker { static var highestUnlockedLevel = 1 var currentLevel = 1static func unlock(level: Int) { if level > highestUnlockedLevel { highestUnlockedLevel = level } }static func isUnlocked(level: Int) -> Bool { return level < highestUnlockedLevel }mutating func advance(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(level + 1) }init(name: String){ playerName = name } }var player = Player(name: "Argyrios") player.complete(1)print("highest unlocked level is now \(LevelTracker.highestUnlockedLevel)")player = Player(name: "Beto") if player.tracker.advance(5) { print("player is now on level 5") } else { print("level 5 has not yet been unlocked") }

console log 如下

Swift|Swift 方法
文章图片
方法实战.png

    推荐阅读