swift 語言的基礎 - Reference Type / Value Type

  1. Reference Type / Value Type
    1. 官網範例
    2. 使用的時機?
    3. 有關於 Class 與 Struct 的介紹,留待其他章節再補完

Reference Type / Value Type

所有的程式言語的變數大多都有 Reference Type 與 Value Type 的觀念

以下就用 swift 裡 struct / class 兩個看起來很像,但是一個是 reference type ,一個是 value type 來簡單介紹

官網範例


// Value type example
struct S { var data: Int = -1 }
  var a = S()
  var b = a						// a is copied to b
  a.data = 42						// Changes a, not b
  println("\(a.data), \(b.data)")	// prints "42, -1"


// Reference type example
class C { var data: Int = -1 }
var x = C()
var y = x						// x is copied to y
x.data = 42						// changes the instance referred to by x (and y)
println("\(x.data), \(y.data)")	// prints "42, 42"

大意是說 Value Type 的使用,在複製一份給新的變數時,兩個變數彼此的值的修改,是不互相影響的, Reference Type的使用,在複製一份給新的變數時,其實不是真的複製一份,而是把當下的記憶體位址告訴新變數,新變數的修改,值的變化,也會造成舊變數一併被修改。

使用的時機?

使用時機的考量點在於–對值的修改,會不會/有沒有必要 影響到其他的變數。

有關於 Class 與 Struct 的介紹,留待其他章節再補完


轉載請註明來源,歡迎對文章中的引用來源進行考證,歡迎指出任何有錯誤或不夠清晰的表達。可以郵件至 [email protected]