-4

I searched on SO but did not find any related question.

I was referring to online swift programming language resource and I found following piece of code:

let emptyArray = [String]()
let emptyDictionary = [String: Float]()

My question is why use let keyword and when?

I need an explanation so I can understand the fundamentals correctly.

Edit:

What will happen internally for the above line and when I should use them?

Draken
  • 3,134
  • 13
  • 34
  • 54
Priyank Sheth
  • 2,352
  • 19
  • 32
  • Read the Swift ebook from Apple. – dasdom Jun 02 '15 at 09:49
  • Apple doc: [Swift basics](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html) – Eric Aya Jun 02 '15 at 09:49
  • why people down voted this question. I am new to this language completely. – Priyank Sheth Jun 02 '15 at 09:52
  • The rule of thumb is to always use `let` (immutable) unless it's absolutely necessary for you to use `var` (mutable). – yusuke024 Jun 02 '15 at 09:55
  • 2
    People is voting down because it seems you didn't try hard enough to find the answer for your question before ask, as the use of "let" is clearly documented in the apple documentation. – Icaro Jun 02 '15 at 09:57
  • See http://stackoverflow.com/questions/24002092/what-is-the-difference-between-let-and-var-in-swift. – Martin R Jun 02 '15 at 10:02
  • For them who down voted this question: @Dheeraj gave answer which I was looking for. – Priyank Sheth Jun 02 '15 at 10:12

2 Answers2

3

From apple documentation:

Constants and variables associate a name (such as maximumNumberOfLoginAttempts or welcomeMessage) with a value of a particular type (such as the number 10 or the string "Hello"). The value of a constant cannot be changed once it is set, whereas a variable can be set to a different value in the future.

let maximumNumberOfLoginAttempts = 10
var currentLoginAttempt = 0

The following code:

let emptyArray = [String]()
let emptyDictionary = [String: Float]()

as the variable names suggest will create an emptyArray and an emptyDictionary that cannot be changed and will be forever empty.

Icaro
  • 14,585
  • 6
  • 60
  • 75
0

You can use let keyword when your array or disctionary will not get modified anywhere in the code that means it is constant. When you declared array or dictionary as

let emptyArray = [String]()
let emptyDictionary = [String: Float]()

then emptyArray is initialized with 0 String values in it means it is initialized but empty. Similarly emptyDictionary is initialized with 0 items of type [String: Float] in it.

Ashvini
  • 342
  • 3
  • 11