值类型&&引用类型

Author Avatar
大朕东 12月 17, 2016

Swift里面,值类型指的是 enumstruct,引用类型指的是class。让我们看看它们的区别。

###值类型 diff 引用类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct Address {
    var street: String
}
struct Person {
    var name: String
    var age: Int
    var address: Address
}
var myAddress = Address(street: "广州大道东🙈")
var DaDong = Person(name: "大朕东", age: 19, address: myAddress)
///一天,大东去了北京
myAddress.street = "北京香格里拉酒店🐒"
DaDong.address // 广州大道东🙈 ??

我明明改了myAddress的的参数,为什么DaDong这个变量没有改?让我们看看class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Address {
    var street: String
    init(street: String) {
        self.street = street
    }
}
class Person {
    var name: String
    var age: Int
    var address: Address
    init(name: String, age: Int, address: Address) {
        self.name = nam
        self.age = age
        self.address = address
    }
}
var myAddress = Address(street: "广州大道东🙈")
var DaDong = Person(name: "大朕东", age: 18, address: myAddress)
///一天,大东去了北京
myAddress.street = "北京香格里拉酒店🐒"
DaDong.address // 北京香格里拉酒店🐒 ??

####结论

1
2
var myAddress = Address(street: "广州大道东🙈")
var DaDong = Person(name: "大朕东", age: 19, address: myAddress)

看这两行代码,用struct实例对象时,其实我们传给Dadong的address是myAddress的一个拷贝值;而相对于class,在实例DaDong这个变量时,传给address只是一个引用,相当于Dadong的address和myAddress指向的是同一块内存空间,这样,改变了myAddress的值,Dadong的address也会随之改变。

值类型
引用类型