众所周知,类是引用类型,而结构和枚举是值类型。这意味着类对象共享该对象的单个实例,并在传递给任何函数或新对象时传递相同的引用,而值类型是创建其副本并仅传递值的类型
如果我们尝试更改类中的任何变量,那就很简单
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
}
}
将会显示下面
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教程和代码关注专栏
- 请关注我的专栏 SwiftUI教程与源码
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。