Enforced immutability: Difference between revisions

Content added Content deleted
m (→‎{{header|Ring}}: Remove vanity tags)
(Add Swift)
Line 1,054: Line 1,054:
b[1] = 100; // returns [1, 100, 3]
b[1] = 100; // returns [1, 100, 3]
b.freeze; // make b immutable
b.freeze; // make b immutable
b[1] = 2; // throws an error ("Attempted write to immutable object.")
b[1] = 2; // throws an error ("Attempted write to immutable object.")</lang>

</lang>
=={{header|Swift}}==
Swift has a notion of immutable values built into the language.
<lang swift>let a = 1
a = 1 // error: a is immutable
var b = 1
b = 1</lang>

It also extends this to higher level data structures. For example Swift has a notion of value types vs reference types.

<lang swift>/// Value types are denoted by `struct`s
struct Point {
var x: Int
var y: Int
}

let p = Point(x: 1, y: 1)
p.x = 2 // error, because Point is a value type with an immutable variable

/// Reference types are denoted by `class`s
class ClassPoint {
var x: Int
var y: Int

init(x: Int, y: Int) {
self.x = x
self.y = y
}
}

let pClass = ClassPoint(x: 1, y: 1)
pClass.x = 2 // Fine because reference types can be mutated, as long as you are not replacing the reference</lang>

Value types are always passed by value. This applies to collections in Swift.

<lang swift>
// A common Swift beginner trap
func addToArray(_ arr: [Int]) {
var arr = arr // Trying to modify arr directly is an error, parameters are immutable
arr.append(2)
}

let array = [1]
addToArray(array)
print(array) // [1], because value types are pass by copy, array is immutable</lang>


=={{header|Tcl}}==
=={{header|Tcl}}==