- 作者: Liwx
- 郵箱: 1032282633@qq.com
- 源碼: 需要
源碼
的同學(xué), 可以在評(píng)論區(qū)
留下您的郵箱
iOS Swift 語(yǔ)法
底層原理
與內(nèi)存管理
分析 專題:【iOS Swift5語(yǔ)法】00 - 匯編
01 - 基礎(chǔ)語(yǔ)法
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): 通過(guò)實(shí)例對(duì)象調(diào)用
-
類型方法
(Type Method): 通過(guò)類型調(diào)用
, 用static
或者class
關(guān)鍵字定義
-
class Car {
static var count = 0
init() {
Car.count += 1
}
static func getCount() -> Int {
// 以下幾個(gè)等價(jià)
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í)例對(duì)象
- 在
類型方法
中代表類型
- 在類型方法
static func getCount
中- 類型存儲(chǔ)屬性
count
等價(jià)于self.count
囚聚、Car.self.count
、Car.count
- 類型存儲(chǔ)屬性
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 // 如果方法沒(méi)有用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
前面加個(gè)@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) // 如果沒(méi)有用 @discardableResult修飾: warning: Result of call to 'moveX(deltaX:)' is unused
iOS Swift 語(yǔ)法
底層原理
與內(nèi)存管理
分析 專題:【iOS Swift5語(yǔ)法】下一篇: 10 - 下標(biāo)
上一篇: 08 - 屬性