September Morn Update
This commit is contained in:
parent
4e2d22a71d
commit
aac6731f2c
6856 changed files with 141342 additions and 21127 deletions
|
|
@ -0,0 +1,4 @@
|
|||
let a = 1
|
||||
a = 1 // error: a is immutable
|
||||
var b = 1
|
||||
b = 1
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
/// 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
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
// 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
|
||||
Loading…
Add table
Add a link
Reference in a new issue