Fork me on GitHub

以撸代码的形式学习Swift-11:方法(Methods)

方法是与某些特定类型相关联的函数
实例方法为给定类型的实例封装了具体的任务与功能
类、结构体、枚举都可以定义实例方法,也都可以定义类型方法
在OC中,类是唯一能定义方法的类型

1 实例方法 (Instance Methods)

  • 实例方法只能被它所属的类的某个特定实例调用
1
2
3
4
5
6
7
8
9
10
11
12
class Counter {
var count = 0
func increment() {
count += 1
}
func incrementBy(amount: Int) {
count += amount
}
func reset() {
count = 0
}
}
  • 方法的局部参数名称和外部参数名称 (Local and External Parameter Names for Methods)
1
2
3
4
5
6
7
8
class Counter2 {
var count: Int = 0
func incrementBy(amount: Int, numberOfTimes: Int) {
count += amount * numberOfTimes
}
}
let counter = Counter2()
counter.incrementBy(amount: 5, numberOfTimes: 3)
  • self 属性(The self Property):self完全等同于该实例本身。
    消除方法参数 x 和实例属性 x 之间的歧义:

    1
    2
    3
    4
    5
    6
    struct Point {
    var x = 0.0, y = 0.0
    func isToTheRightOfX(x: Double) -> Bool {
    return self.x > x
    }
    }
  • 在实例方法中修改值类型(Modifying Value Types from Within Instance Methods)
    结构体和枚举的属性不能在它的实例方法中被修改(因为结构体和枚举是值类型),但可通过mutating(可变方法)修改。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    struct Point2 {
    var x = 0.0, y = 0.0
    mutating func moveByX(_ deltaX: Double, y deltaY: Double) {
    x += deltaX
    y += deltaY
    }
    }
    var somePoint = Point2(x: 1.0, y: 1.0)
    somePoint.moveByX(2.0, y: 3.0)
  • 在可变方法中给 self 赋值(Assigning to self Within a Mutating Method)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    struct Point3 {
    var x = 0.0, y = 0.0
    mutating func moveByX(_ deltaX: Double, y deltaY: Double) {
    self = Point3(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
    }
    }
    }

2 类型方法 (Type Methods)

static class
在类型方法的方法体(body)中,self指向这个类型本身,而不是类型的某个实例。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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: level) {
currentLevel = level
return true
} else {
return false
}
}
}
class Player {
var tracker = LevelTracker()
let playerName: String
func completedLevel(level: Int) {
LevelTracker.unlockLevel(level: level + 1)
tracker.advanceToLevel(level: level + 1)
}
init(name: String) {
playerName = name
}
}

playground文件在andyRon/LearnSwift

坚持原创技术分享,您的支持将鼓励我继续创作!
  • 本文标题: 以撸代码的形式学习Swift-11:方法(Methods)
  • 本文作者: AndyRon
  • 发布时间: 2017年07月03日 - 13:41
  • 最后更新: 2018年09月20日 - 01:39
  • 本文链接: http://andyron.com/2017/swift-11.html
  • 版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!