Constants and Variables
Reference Type
我們用 let
定義一個 Window
物件(instance):
let window = Window(frame: frame)
這表示我有一個 constant window
reference。所以 window
被宣告以後就不能改了。因此以下的操作會發生錯誤:
let window = Window(frame: frame)
window = Window(frame: frame)
// error: Cannot mutate a constant!
在 window = Window(frame: frame)
會發生 compiled time 的錯誤。
但是我們還是可以操作 window
本身的 properties:
let window
window.title = "Hello!"
這樣是合法的,因為我們操作的是 Window
的 properties。
Value Types
我們定義 2 個 Point
物件(instance), point2
為 constant:
var point1 = Point(x: 0.0, y: 0.0)
let point2 = Point(x: 0.0, y: 0.0)
接著我們修改這 2 個物件(instance)的 properties:
point1.x = 5
// point1 = (5, 0)
point2.x = 5
// error: Cannot mutate a constant!
會發現,我們修改 point2
時,會產生 compiled time error。這是因為 point2
為 value type, constant 的意思就是「值」不能被修改。
除此之外, structure 還有一些很特別的地方要注意。
下一篇: Mutating a Structure