Swift語法 Swift5 【09 - 方法】


  • 作者: 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.countCar.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 - 屬性


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請通過簡信或評論聯(lián)系作者。

友情鏈接更多精彩內(nèi)容