Swift

Swift - Methods

2018-10-23  本文已影响6人  ienos

Support

Classes / Structures / Enumerations

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)

类方法

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
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读