- 作者: Liwx
- 郵箱: 1032282633@qq.com
- 源碼: 需要
源碼的同學(xué), 可以在評論區(qū)留下您的郵箱
iOS Swift 語法
底層原理與內(nèi)存管理分析 專題:【iOS Swift5語法】00 - 匯編
01 - 基礎(chǔ)語法
02 - 流程控制
03 - 函數(shù)
04 - 枚舉
05 - 可選項(xiàng)
06 - 結(jié)構(gòu)體和類
07 - 閉包
08 - 屬性
09 - 方法
10 - 下標(biāo)
11 - 繼承
12 - 初始化器init
13 - 可選項(xiàng)
目錄
- 01-方法(Method)
- 02-mutating
- 03-@discardableResult
01-方法(Method)
-
枚舉、結(jié)構(gòu)體、類都可以定義實(shí)例方法、類型方法-
實(shí)例方法(Instance Method): 通過實(shí)例對象調(diào)用 -
類型方法(Type Method): 通過類型調(diào)用, 用static或者class關(guān)鍵字定義
-
class Car {
static var count = 0
init() {
Car.count += 1
}
static func getCount() -> Int {
// 以下幾個等價
return count
// return Car.count
// return self.count // self類型方法中代表類型
// return Car.self.count
}
}
let c0 = Car()
let c1 = Car()
let c2 = Car()
print(Car.getCount()) // 3
-self
- 在
實(shí)例方法中代表實(shí)例對象 - 在
類型方法中代表類型 - 在類型方法
static func getCount中- 類型存儲屬性
count等價于self.count、Car.self.count、Car.count
- 類型存儲屬性
02-mutating
-
結(jié)構(gòu)體和枚舉是值類型, 默認(rèn)情況下,值類型的屬性不能被自身的實(shí)例方法修改- 在
func關(guān)鍵字簽加mutating可以允許這種修改行為
- 在
- 結(jié)構(gòu)體
mutating使用
struct Point {
var x = 0.0, y = 0.0
mutating func moveBy(deltaX: Double, deltaY: Double) {
x += deltaX // 如果方法沒有用mutating修飾 error: left side of mutating operator isn't mutable: 'self' is immutable
y += deltaY
// self = Point(x: x + deltaX, y: y + deltaY) // 本質(zhì)也是修改x,y屬性 error: cannot assign to value: 'self' is immutable
}
}
- 枚舉
mutating使用
enum StateSwitch {
case low, middle, high
mutating func next() { // mutating修飾枚舉實(shí)例方法 實(shí)例方法內(nèi)部才能修改屬性
switch self {
case .low:
self = .middle
case .middle:
self = .high
case .high:
self = .low
}
}
}
var s = StateSwitch.low
print(s) // low
s.next()
print(s) // middle
s.next()
print(s) // high
s.next()
print(s) // low
03-@discardableResult
- 在
func前面加個@discardableResult, 可以消除: 函數(shù)調(diào)用后返回值未被使用的警告
struct Point {
var x = 0.0, y = 0.0
@discardableResult mutating func moveX(deltaX: Double) -> Double {
x += deltaX
return x
}
}
var p = Point()
p.moveX(deltaX: 10) // 如果沒有用 @discardableResult修飾: warning: Result of call to 'moveX(deltaX:)' is unused
iOS Swift 語法
底層原理與內(nèi)存管理分析 專題:【iOS Swift5語法】下一篇: 10 - 下標(biāo)
上一篇: 08 - 屬性