0

I'm using playgrounds to learn Swift and I noticed something strange when trying to set optionals on var and let. Below is the code with output:

var num1: Int?
print(num1) //Output: "nil\n"

let num2: Int?
print(num2) //Output: Error: Constant num2 used before initialized

I do not understand why 'var' gets initialized with nil and 'let' is uninitialized when made optional.

Hamish
  • 78,605
  • 19
  • 187
  • 280
Mohammed Azhar
  • 260
  • 4
  • 18
  • My guess is language set `nil` as default value when you create `var` but do not do this when you declare `let` – JuicyFruit Mar 16 '17 at 08:13
  • 1
    Related: http://stackoverflow.com/questions/34969234/why-doesnt-swift-allow-setting-value-of-an-optional-constant-after-object-initi. – Martin R Mar 16 '17 at 08:16
  • @Hamish: That is what I was looking for. How do you find the (correct) duplicates so quickly? – Martin R Mar 16 '17 at 08:19
  • @MartinR Combination of keeping them favourited and google searches :) I sometimes remember the name of the person who answered / asked the question – which helps the search. – Hamish Mar 16 '17 at 08:20

1 Answers1

0

var is variable, you can declare it without initialisation. But let is constant, you should initialise it’s value, i.e.

    var num1: Int?
    print(num1) //Output: "nil\n"

    let num2: Int = 20
    print(num2)
Sagar Chauhan
  • 5,715
  • 2
  • 22
  • 56
  • You can also visit here : http://stackoverflow.com/questions/24002092/what-is-the-difference-between-let-and-var-in-swift – Sagar Chauhan Mar 16 '17 at 08:16
  • 4
    That is not quite correct (or misleading). You must assign a value to a constant before it is used, but not necessarily in its declaration. Example: `let num2: Int; num2 = 5 ; print(num2)` – Martin R Mar 16 '17 at 08:18