程序员Swift5.0探究

Swift5探究:值类型与引用类型

2020-05-19  本文已影响0人  卢叁

值类型

在 Swift 中,struct、enum、 tuple 都是值类型。而平时使用的 Int, Double,Float,String,Array,Dictionary,Set 其实都是用结构体实现的,所以也是值类型。值类型的赋值为深拷贝(Deep Copy),值语义(Value Semantics)即新对象和源对象是独立的,当改变新对象的属性,源对象不会受到影响。代码如下:

struct Coordinate {
   var x: Double
   var y: Double
}
 //值类型,深拷贝
 var coordA = Coordinate(x: 0, y: 0)
 var coordB = coordA
 coordA.x = 100.0
 print("coordA.x -> \(coordA.x)")
 print("coordB.x -> \(coordB.x)")
  //打印内存地址
withUnsafePointer(to: &coordA) { print("\($0)") }
withUnsafePointer(to: &coordB) { print("\($0)") }
coordA.x -> 100.0
coordB.x -> 0.0
0x00007ffeea5012d0
0x00007ffeea5012c0

引用类型

在 Swift 中,class 和闭包是引用类型。引用类型的赋值是浅拷贝(Shallow Copy),引用语义(Reference Semantics)即新对象和源对象的变量名不同,但其引用(指向的内存空间)是一样的,因此当使用新对象操作其内部数据时,源对象的内部数据也会受到影响。代码如下:

 //class和闭包是引用类型(即所有实例共享一份数据拷贝)
  let catA = Cat()
  let catB = catA
  catA.height = 50.0
  print("dogA.height -> \(catA.height)")
  print("dogB.height -> \(catB.height)")
 //打印内存地址
 print(Unmanaged.passUnretained(catA).toOpaque()) 
 print(Unmanaged.passUnretained(catB).toOpaque())
 dogA.height -> 50.0
 dogB.height -> 50.0
 0x00006000009e7100
 0x00006000009e7100
上一篇 下一篇

猜你喜欢

热点阅读