美文网首页
Swift - 方法(Method)

Swift - 方法(Method)

作者: iVikings | 来源:发表于2020-06-22 18:07 被阅读0次

方法(Method)

枚举、结构体、类 都可以定义实例方法、类型方法

  • 实例方法(Instance Method):通过实例对象调用
  • 类型方法(Type Method):通过类型调用,用 staticclass 关键字定义
class Car {
    static var count: Int = 0
    init() {
        Car.count += 1
    }
    static func getCount() -> Int { count }
}
  • self

    • 在实例方法中代表实例对象
    • 在类型方法中代表类型
  • 在类型方法 static func getCount

    • cout 等价于 self.coutCar.self.coutCar.out

mutating

结构体枚举 是值类型,默认情况下,值类型的属性不能被自身的实例方法修改

func 关键字前加 mutating 可以允许这种修改行为

struct Point {
    var x = 0.0, y = 0.0
    mutating func moveBy(deltaX: Double, deltaY: Double) {
        x += deltaX
        y += deltaY
    }
}

enum StateSwitch {
    case low, middle, high
    mutating func next() {
        switch self {
        case .low:
            self = .middle
        case .middle:
            self = .high
        case .high:
            self = .low
    }
}

@discardableResult

func 前面加个 @discardableResult,可以消除:函数调用后返回值未被使用的警告⚠️

struct Point {
    var x = 0.0, y = 0.0
    @discardableResult mutating
    func moveBy(deltaX: Double) -> Double {
        x += deltaX
        return x
    }
}

var p = Point()
p.moveBy(deltaX: 10)

相关文章

网友评论

      本文标题:Swift - 方法(Method)

      本文链接:https://www.haomeiwen.com/subject/qolffktx.html