Mutating a Structure

Structuremethod 有一個很特別的規定,依照 Swift 的定義:

“Structures and enumerations are value types. By default, the properties of a value type cannot be modified from within its instance methods.”

也就是說,在 structure 裡面的 method,都不能去修改 structure 的任何 properties

struct Point {
   var x, y: Double

   func moveToTheRightBy(dx: Double) {
       x += dx
    // error: cannot assign to 'x' in 'self'
   }
}

以上的程式碼在 compiled time 就會出錯,系統會警告你不能修改 x


但還是有可以修改的方法,要在 func 前面加上 keyword mutating

struct Point {
   var x, y: Double

   mutating func moveToTheRightBy(dx: Double) {
   x += dx
   }
}

var point = Point(x: 0.0, y: 0.0)

point.moveToTheRightBy(200.0)
// point (x:200.0, y:0.0)

只要執行 moveToTheRightBy() 就可以順利的修改 x 的值。


如果把 var point = Point(x: 0.0, y: 0.0) 改成 let point = Point(x: 0.0, y: 0.0)

struct Point {
   var x, y: Double

   mutating func moveToTheRightBy(dx: Double) {
   x += dx
   }
}

let point = Point(x: 0.0, y: 0.0)

point.moveToTheRightBy(200.0)
// Error: Cannot mutate a constant!

就會發生錯誤,因為 structurevalue-type,設定成 constant 之後,是沒有辦法改變任何 properties 的。
(無論你有沒有加上 mutating)

下一篇: Enumerations