PDF版 ePub版

方法 - Methods

实例方法

    class Counter {
var count = 0
func increment() {
count++
}
func incrementBy(amount: Int) {
count += amount
}
func reset() {
count = 0
}
}

Counter 可以定义三种实例方法：

• increment 让计数器按一递增
• incrementBy(amount: Int) 让计数器按一个指定的整数值递增
• reset 将计数器重置为 0

Counter 这个类还声明了一个可变属性 count，用它来保持对当前计数器值的追踪。

    let counter = Counter()
// the initial counter value is 0
counter.increment()
// the counter's value is now 1
counter.incrementBy(5)
// the counter's value is now 6
counter.reset()
// the counter's value is now 0

方法的局部参数名称和外部参数名称

    class Counter {
var count: Int = 0
func incrementBy(amount: Int, numberOfTimes: Int) {
count += amount * numberOfTimes
}
}

incrementBy 方法有两个参数：amountnumberOfTimes。默认地，Swift 仅把 amount 当做一个局部名称，但是把 numberOfTimes 既看作局部名称又看做外部名称。调用方法如下：

    let counter = Counter()
counter.incrementBy(5, numberOfTimes: 3)
// counter value is now 15

    func incrementBy(amount: Int, #numberOfTimes: Int) {
count += amount * numberOfTimes
}

self 属性

    func increment() {
self.count++
}

    struct Point {
var x = 0.0, y = 0.0
func isToTheRightOfX(x: Double) -> Bool {
return self.x > x
}
}
let somePoint = Point(x: 4.0, y: 5.0)
if somePoint.isToTheRightOfX(1.0) {
println("This point is to the right of the line where x == 1.0")
prints "This point is to the right of the line where x == 1.0"

在实例方法中修改值类型

    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)
println("The point is now at (\(somePoint.x), \(somePoint.y))")
// 输出 "The point is now at (3.0, 4.0)"

    let fixedPoint = Point(x: 3.0, y: 3.0)
fixedPoint.moveByX(2.0, y: 3.0)
// this will report an error

在变异方法中给 self 赋值

    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
}
ovenLight = TriStateSwitch.Low
ovenLight.next()
// ovenLight is now equal to .High
ovenLight.next()
// ovenLight is now equal to .Off

类型方法

    class SomeClass {
class func someTypeMethod() {
// type method implementation goes here
}
}
SomeClass.someTypeMethod()

    struct LevelTracker {
static var highestUnlockedLevel = 1
static func unlockLevel(level: Int) {
if level > highestUnlockedLevel
{ highestUnlockedLevel = level }
}
static func levelIsUnlocked(level: Int) -> Bool {
return level <= highestUnlockedLevel
}
var currentLevel = 1
mutating func advanceToLevel(level: Int) -> Bool {
if LevelTracker.levelIsUnlocked(level) {
currentLevel = level
return true
} else {
return false
}
}

LevelTracker 结构体监测任何玩家已解锁的最高级别。该值被存储在成为 highestUnlockedLevel 的静态属性中。

LeveTracker 还定义了两个类型函数与 highestUnlockedLevel 配合工作。第一个为 unockLevel 类型函数，一旦新的级别被解锁，该函数会更新 highestUnlockedLevel 的值。第二个为 levelIsUnocked 便利型函数，若某个给定级别数已经被解锁，该函数则返回 true。（注：没用使用 LevelTracker.highestUnlockedLevel，这个类型方法还是能够访问静态属性 highestUnlockedLevel。）

    class Player {
var tracker = LevelTracker()
let playerName: String
func completedLevel(level: Int) {
LevelTracker.unlockLevel(level + 1)
}
init(name: String) {
playerName = name

Player 类使用 LevelTracker 来监测该玩家的游戏进程。它也提供 competedLevel 方法，一旦玩家完成某个指定等级，调用该方法。该方法为所有玩家解锁下一个级别并将当前玩家进程更新为下一个级别。（忽略了 advanceToLevel 布尔返回值，因为之前调用上行时就知道了这个等级已经被解锁了。）

    var player = Player(name: "Argyrios")
player.completedLevel(1)
println("highest unlocked level is now \(LevelTracker.highestUnlockedLevel)")
// prints "highest unlocked level is now 2"

    player = Player(name: "Beto")
// prints "level 6 has not yet been unlocked"