Swift - Methods
2018-10-23 本文已影响6人
ienos
Support
Classes / Structures / Enumerations
Self
- 不需要写 self,只使用属性或方法名在方法中,swift 默认引用实例的属性或者方法
- 当参数名和属性名一致,此时需要使用 self 区分
Structures / Enumerations 默认不能在实例方法中修改属性值
值类型的实例方法中修改也可以直接修改 self 属性值
struct Point {
var x = 0.0, y = 0.0
mutating func moveBy(x deltax: Double, y deltaY: Double) {
// x += deltax
// y += deltax
// 分配 self 在 mutating 方法中
self = Point(x: x + deltax,y: y + deltay)
}
}
// 如果是常量则不能修改,即使属性是可变的
var somePoint = Point(x: 1.0, y: 1.0)
somePoint.moveBy(x: 2.0, y: 3.0)
类方法
- 在 func 前面加 static 声明为类方法
- class 关键字允许重写父类实现方法
- self 区分方法参数和类型属性
struct LevelTracker {
static var highestUnlockedLevel = 1
var currentLevel = 1
static func unlock(_ level: Int) {
if level > highestUnlockedLevel {
highestUnlockedLevel = level
}
}
static func isUnlocked(_ level: Int) -> Bool {
return level <= highestUnlockedLevel
}
@discardableResult // 参见 Swift - Attributes
mutating func advance(to level: Int) -> Bool {
if LevelTracker.isUnlocked(level) {
currentLevel = level
return true
}else {
return false
}
}
}