5

Is there a difference between how following bits of code work?

let x: Int = 4

and

let x: Int
x = 4
Hamish
  • 78,605
  • 19
  • 187
  • 280
Mig N.
  • 53
  • 3
  • 2
    @KSigWyatt There's nothing wrong with initialising a `let` constant after its declaration, given that you cannot read it before initialising it. Why would "proper programming style" suggest making it a `var`? – Hamish Oct 18 '16 at 13:59
  • 3
    @KSigWyatt: There are cases where you declare a constant first and later assign a value to it (exactly once, but perhaps depending on some conditions). Example here: http://stackoverflow.com/a/30190231/1187415. – Martin R Oct 18 '16 at 14:00

2 Answers2

9

This one:

let x: Int = 4

creates a non-optional variable x and initialises it to 4. x can be used without issue.

This one:

let x: Int
// Cannot do anything with x yet
x = 4

creates a non-optional variable x with no defined value. It cannot be used without first assigning it to a value, either directly (as in your example) or by the result of some other statement. If you do try and use it, you'll get a compile-time error.

Ed King
  • 1,833
  • 1
  • 15
  • 32
-1

The only difference is that on the first one you are declaring a variable and assigning it at the same time, and the second one you declare it first and then assign it.

But there is no mayor difference.

Mago Nicolas Palacios
  • 2,501
  • 1
  • 15
  • 27
  • 1
    ...no difference except that you're using two instructions vs. 1 by using the second style, which is marginally less efficient. Arguably, though, it makes your code less readable, which is an excellent argument against using the more verbose style. – Joshua Nozzi Oct 18 '16 at 13:54
  • Let's not split hairs. "No major difference" is not the same thing as a nuanced answer explaining what the *minor* differences actually are. – Joshua Nozzi Oct 18 '16 at 13:56