方法的语法和函数一致,在某个实例(类,结构体,枚举)定义的函数就实例方法。
self
类似于Java的“this”关键字,指定自己。
在实例方法修改值类型属性的值
默认情况下,值类型的实例方法是不能修改它的属性值
struct StepCounter {
var step: Int = 0
func add(by: Int) { // 编译器会报错,提示不能修改属性值
self.step += by
}
}
如果值类型实例需要改变属性值,需要在方法前加上“mutating”关键字
struct StepCounter {
var step: Int = 0
mutating func add(by: Int) {
self.step += by
}
}
var countor = StepCounter()
countor.add(by: 5)
countor.step // step的值为5
由于class为引用类型,因此不用加上这个关键字(加上竟然报错!!)。
类型方法
同类型属性,在定义方法前,加“static”关键字
class StepCounter {
static var step: Int = 0
static func add(by: Int) {
StepCounter.step += by
}
}
StepCounter.add(by: 100)
StepCounter.step