swift結構體的mutating

Structures and enumerations are value types. By default, the properties of a value type cannot be modified from within its instance methods.
結構體和枚舉都是值類型。默認的,在實例方法內部,值類型的屬性不能被修改。
However, if you need to modify the properties of your structure or enumeration within a particular method, you can opt in to mutating behavior for that method. The method can then mutate (that is, change) its properties from within the method, and any changes that it makes are written back to the original structure when the method ends. The method can also assign a completely new instance to its implicit self property, and this new instance will replace the existing one when the method ends.
然而,如果你需要在一個方法內部修改一個結構體或者枚舉的屬性。你可以選擇mutating那個方法的行爲。這個方法然後就可以變異在方法內部修改屬性值。當方法結束的時候,任何的變化都會返回到原始結構裏邊。這個方法也可以利用他的隱式self屬性賦值給一個新值。
這裏寫圖片描述
分析
因爲你已經申明瞭結構體實例是常量,因此他的素偶偶屬性都不能進行更改了。

發佈了74 篇原創文章 · 獲贊 6 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章