swift mutating 作用

在 Swift 中,structure ??enumeration 被創建之后其值和屬性不可變的,如果你需要在一個修改屬性值,需要給這個方法添加 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.
You can opt in to this behavior by placing the mutating keyword before the func keyword for that method:”
Excerpt From: Apple Inc. “The Swift Programming Language (Swift 3).” iBooks.?


舉個栗子:

struct?Person?{
????var?name:String!?=?"Zhang"
????
????mutating?func?setName(?newName:String?)?{
????????name?=?newName
????}
}
var?person?=?Person()
person.name
person.setName(?"Wang"?)

在上面例子中,setName 方法需要修改 immutable 屬性 name,所以前面要加上 mutating。
grateful to have you linux時間設置命令 出差高端神器 孟菲爾斯表演 演員翻唱女版搞怪 知乎 越南旅游 conduct 和implement 樓梯裝踢腳燈好嗎 tubular invader科技 房屋隔音改造 電影海報 日語 31號 華為怎么裝王者榮耀 神牧還是薩滿 機械sata2和sata3 百度格子論文查重 amy和玲玲 籬笆女人狗電視劇第3集 類似青青陌上桑的小說 魯政發121號 希望女兒閱讀答案 red中文意思是什么 fight crime 卡通線稿 8月30是什么節 薔薇少女圖片 血壓不高但頭暈吃啥藥 ps時間軸制作動圖 golang 并發安全 蘇大漫畫墅湖校區地址

Copyright 幫手網 Some Rights Reserved

如反饋或投訴等情況聯系:une35498#163.com

安徽快3组合走势图