第十四节 Swift中的方法

2020-07-12  本文已影响0人  码客南君

Swift 中的方法就是函数,分为实例方法和类型方法。

实例方法在特定类型实例中调用,代码示例

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

Couter 类定义了三个实例方法:

increment()让 count每次增加1;
increment(by Int) 指定每次增加的数
reset() 重置count值为0

类型方法需要在类上调用类型方法,代码示例:

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

SomeClass.someTypeMethod()
上一篇 下一篇

猜你喜欢

热点阅读