SwiftUI mutating 是什麼怎麼用 (2020年教程)

衆所周知,類是引用類型,而結構和枚舉是值類型。這意味着類對象共享該對象的單個實例,並在傳遞給任何函數或新對象時傳遞相同的引用,而值類型是建立其副本並僅傳遞值的類型

若是咱們嘗試更改類中的任何變量,那就很簡單swift

class Employee {
    var name : String
    var teamName : String
init(name: String, teamName: String) {
        self.name = name
        self.teamName = teamName
    }
func changeTeam(newTeamName : String){
        self.teamName = newTeamName
    }
}
var emp1 = Employee(name : "Suneet", teamName:"Engineering")
print(emp1.teamName)    //Engineering
emp1.changeTeam(newTeamName : "Product")
print(emp1.teamName)    //Product

而若是您嘗試在任何值類型中執行相同操做,則會向咱們顯示編譯錯誤.函數

struct Employee {
    var name : String
    var teamName : String
init(name: String, teamName: String) {
        self.name = name
        self.teamName = teamName
    }
func changeTeam(newTeamName : String){
        self.teamName = newTeamName
        //cannot assign to property: 'self' is immutable
    }
}

將會顯示下面code

cannot assign to property: 'self' is immutable

Struct 是值類型,咱們不可以直接修改屬性。所以編譯器會提示咱們作以下修改對象

mark method 'mutating' to make 'self' mutable

它明確指出,在值類型中向任何函數添加突變關鍵字能夠使它們可以修改變量。在內部,當咱們嘗試突變值類型時,它不會mutate其值,但它會mutate持有該值的變量。教程

struct Employee {
    var name : String
    var teamName : String
init(name: String, teamName: String) {
        self.name = name
        self.teamName = teamName
    }
mutating func changeTeam(newTeamName : String){
        self.teamName = newTeamName
    }
    
}
var emp1 = Employee(name : "Suneet", teamName:"Engineering")
print(emp1.teamName)    //Engineering
emp1.changeTeam(newTeamName : "Product")
print(emp1.teamName)    //Product

值類型

  • enum
  • struct
  • Int
  • Double
  • String
  • Array
  • Dictionary
  • Set
  • Tuple

引用類型

  • Functions
  • Closures
  • Class

參考文件

更多SwiftUI教程和代碼關注專欄

相關文章
相關標籤/搜索