self一般是指當(dāng)前執(zhí)行或所有對象
self.屬性/方法 調(diào)用優(yōu)先級: (先private -> public)
1.當(dāng)代碼所在類的 private屬性/方法
2.子類->超類
在繼承環(huán)境中:
superClass中調(diào)用:
self.屬性/方法: 先調(diào)用代碼當(dāng)前類的私有
Bug:
如果superClass中有private 屬性/方法 和subClass 屬性/方法 同名,那就調(diào)用superClass自己的private 屬性/方法
解決:
private 屬性/方法 添加前綴 : 如 p_ 屬性/方法
import Foundation
print("Hello, World!")
class Chang {
var height:Double
private var width:Double {
willSet{
print("super width willSet")
}
}
init(height:Double,width:Double = 3) {
self.width = width
self.height = height
}
func argumentFunc(_ test:Double){
self.width = test
self.testFunc()
}
private func testFunc(){
print("super testFunc")
}
}
class Zheng:Chang{
var width: Double = 15 {
willSet{
print("self width willSet")
}
}
override func argumentFunc(_ test:Double){
super.argumentFunc(test)
}
func testFunc(){
print("super testFunc")
}
}
輸出:
var test2 = Zheng(height:6,width:4)
print(test2.width)
test2.width = 5
print(test2.width)
test2.argumentFunc(6)
print(test2.width)