Swift

2023 年 10 月 8 日

Swift 讓 struct 可以更動自己的 mutating

已複製到剪貼板


Swift 的 struct 預設為 immutable,也就是不可變的,但我們可以透過 mutating 關鍵字來讓 struct 變為 mutable 可變的。

Swift Methods

Swift 的 struct 預設為 immutable 不可變的

雖然說 Swift 的 struct 預設為 immutable 不可變的,但如果我們都是從外面來改變 struct 裡的值的話,可能就不會有感覺。

struct Model {
    var num = 0
}

var model = Model()
model.num += 1 // 從 struct 外對 struct 內的值做變更

這裡如果我們想把「+1」這件事變成一個 func 寫進 stuct 裡,並在外面用呼叫 func 的方式來加一的話,就會遇到問題。

Xcode Warning:Left side of mutating operator isn't mutable 'self' is immutable

Xcode 會說:「Left side of mutating operator isn't mutable: 'self' is immutable」,struct 是不能自己變更自己的。

Swift 的 mutating 關鍵字

要解決這個問題,只要在 func 前加上「mutating」的關鍵字就行了!這會讓 struct 變成 mutable,也就可以在 func 內部對自己的值做更動了。

struct Model {
  
    var num = 0
    
    mutating func increase() {
        num += 1
    }
}

分享文章

已複製到剪貼板

主題文章

查看 Swift

超級感謝

關於 XcodeProject

XcodeProject 創立於 2023,致力於協助開發者探索 Apple 的創新世界,學習在 iOS、iPadOS、macOS、tvOS、visionOS 與 watchOS 上開發 App,發現眾多技術與框架,讓開發者獲得更多能力。


Contacts

Ricky Chuang

XcodeProject

RickyChuang.xcodeproj@gmail.com

XcodeProject 聯絡

contact.xcodeproj@gmail.com

最新文章