The Traveled iOS Developer's Guide

值类型 && 引用类型

2016-12-17  本文已影响101人  大朕东

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

值类型 diff 引用类型

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

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 //      北京香格里拉酒店🐒  ??

结论

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也会随之改变。

值类型
引用类型
上一篇下一篇

猜你喜欢

热点阅读