mutating關(guān)鍵字

如果在類(lèi)中使用mutating關(guān)鍵字,編譯器會(huì)報(bào)錯(cuò)'mutating' isn't valid on methods in classes or class-bound protocols。

因?yàn)轭?lèi)是引用類(lèi)型,而結(jié)構(gòu)體和枚舉是值類(lèi)型,在值類(lèi)型的實(shí)例方法中,值類(lèi)型的屬性默認(rèn)是不可以被修改的。為了修改值類(lèi)型的屬性值,需要在它的實(shí)例方法上使用mutating關(guān)鍵字。

struct LSStack {
    private var items = [Int]()

    mutating func push(item: Int) {
        items.append(item) 
    }
}

var s = LSStack()
s.push(item: 1)

上面是一個(gè)簡(jiǎn)單的棧的例子,需要改變值類(lèi)型LSStack中屬性items的值,則需要在push方法前添加mutating關(guān)鍵字。

// LSStack.push(item:)
sil hidden @$s4main7LSStackV4push4itemySi_tF : $@convention(method) (Int, @inout LSStack) -> () {
// %0 "item"                                      // users: %5, %2
// %1 "self"                                      // users: %6, %3
bb0(%0 : $Int, %1 : $*LSStack):
  debug_value %0 : $Int, let, name "item", argno 1 // id: %2
  debug_value_addr %1 : $*LSStack, var, name "self", argno 2 // id: %3
  %4 = alloc_stack $Int                           // users: %5, %11, %9
  store %0 to %4 : $*Int                          // id: %5
  %6 = begin_access [modify] [static] %1 : $*LSStack // users: %10, %7
  %7 = struct_element_addr %6 : $*LSStack, #LSStack.items // user: %9
  // function_ref Array.append(_:)
  %8 = function_ref @$sSa6appendyyxnF : $@convention(method) <τ_0_0> (@in τ_0_0, @inout Array<τ_0_0>) -> () // user: %9
  %9 = apply %8<Int>(%4, %7) : $@convention(method) <τ_0_0> (@in τ_0_0, @inout Array<τ_0_0>) -> ()
  end_access %6 : $*LSStack                       // id: %10
  dealloc_stack %4 : $*Int                        // id: %11
  %12 = tuple ()                                  // user: %13
  return %12 : $()                                // id: %13
} // end sil function '$s4main7LSStackV4push4itemySi_tF'

將上述代碼轉(zhuǎn)為sil發(fā)現(xiàn),push參數(shù)中除了第一個(gè)顯示的Int類(lèi)型參數(shù),還有一個(gè)使用@inout修飾的LSStack,通過(guò)結(jié)構(gòu)體元素地址進(jìn)行修改。

func swap( a: inout Int, b: inout Int) {
    let temp : Int = a
    a = b
    b = temp
}

var a:Int = 10
var b:Int = 20

swap(&a, &b)

print(a)
print(b)

函數(shù)參數(shù)默認(rèn)是不可變,如果想要修改函數(shù)參數(shù)則需要使用inout進(jìn)行修飾,同時(shí)傳參時(shí)需要傳入地址

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

相關(guān)閱讀更多精彩內(nèi)容

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