八、Swift 类和结构体的区别——值传递与指针传递

1. 结构体、枚举是值类型 Structures and Enumerations Are Value Types

值类型:当一个常量/变量被赋值给一个常量/变量,或者被传递给一个函数时,使用的是它的副本。也就是值传递,与之对应的是引用传递/指针传递。

Swift中的基本数据类型:integers, floating-point numbers, Booleans, strings, arrays and dictionaries 都是值类型。所以当他们在代码中传递的时候,都是传递的拷贝/副本。

struct Resolution {
    var width = 0
    var height = 0
}
let hd = Resolution( 1920, height: 1080)
var cinema = hd

上面的代码会创建hd的副本,然后将副本赋值给cinema,所以hd与cinema是完全不同的实例。

    cinema.width = 2048
    println("cinema is now (cinema.width) pixels wide")
    // prints "cinema is now 2048 pixels wide"

    println("hd is still (hd.width) pixels wide")
    // prints "hd is still 1920 pixels wide"

枚举也一样,是值类型。

2. 类是引用类型Classes Are Reference Types

引用类型:当一个常量/变量被赋值给一个常量/变量,或者被传递给一个函数时,使用的是源对象的引用,他们指向同一个对象。

class VideoMode {
    var resolution = Resolution()
    var interlaced = false
    var frameRate = 0.0
    var name: String?
}
let tenEighty = VideoMode()
tenEighty.resolution = hd
tenEighty.interlaced = true
tenEighty.name = "1080i"
tenEighty.frameRate = 25.0

let alsoTenEighty = tenEighty
alsoTenEighty.frameRate = 30.0
println("The frameRate property of tenEighty is now (tenEighty.frameRate)")
// prints "The frameRate property of tenEighty is now 30.0"

3. 判断两个变量/常量是否指向同一个实例 Identity Operators

等于(===)

不等于(!==)

if tenEighty === alsoTenEighty {
  println("tenEighty and alsoTenEighty refer to the same VideoMode instance.")
}
// prints "tenEighty and alsoTenEighty refer to the same VideoMode instance."

== 与 === 的区别:

“Identical to”(===) 指两个变量/常量指向一个类的同一个实例

“Equal to”(==) 指两个变量/常量值相等“equal” or “equivalent” in value。当你定义了自己的类时,你可以自己决定两个实例“equal”的条件,这在Equivalence Operators. 进行介绍

4. String、Array、Dictionary的赋值和复制特性 Assignment and Copy Behavior for Strings, Arrays, and Dictionaries

String、Array、Dictionar与结构体类似,传递或赋值是都是操作副本。实际上使用的类似于懒加载的技术,需要使用时才会真正拷贝,所以效率依然很高。

所以Swift中的String、Array、Dictionar与Objective-C中的NSString、NSArray、NSDictionary有很大不同。

Objective-C中的NSString、NSArray、NSDictionary都是使用类来实现的,传递和赋值使用的同一个实例的引用,而不是拷贝。

原文地址:https://www.cnblogs.com/actionke/p/4226282.html