-2

I'm studying arrays in Swift and in my book first they write:

let numbers = [0, 1, 2, 3]

but then write:

var numbers = [0, 1, 2, 3]

I know that let denotes constants and var refers to variables, but practically what changes from an array declared as constant and an array declared as variable?

Rob
  • 415,655
  • 72
  • 787
  • 1,044
Bug-Gy
  • 61
  • 1
  • 7

3 Answers3

5

since arrays in swift are structs declaring an array with let not only prevents you from assigning a new value to it but also prevents you from changing its contents

so for example:

    let arr = [0, 1, 2]
    arr[0] = 10 //will not compile
    arr = [] //will not compile
giorashc
  • 13,691
  • 3
  • 35
  • 71
  • 1
    Thank you, all answers are good and useful but in my opinion yours is more complete. Solved! – Bug-Gy Jul 07 '19 at 12:07
2

The array declared as constant is immutable.

Its size and contents cannot be changed.

bart
  • 1,003
  • 11
  • 24
1

you can not change/add/remove elements of array when it is declared with let. if you want make any changes with an array, you need to declare with var.

Li Jin
  • 1,879
  • 2
  • 16
  • 23