JW.ZG
JW.ZG

Reputation: 611

Swift: Do we need to declare a variable before using it?

I am very new to swift. And I met this problem quite by accident.

This is an example in The Swift Programming Language(Swift 2.1).

let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
    if score > 50 {
        teamScore += 3
    } else {
        teamScore += 1
    }
}
print(teamScore)

As can be seen, score is a variable in the code section above. But it's apparently not declared before using it. I mean, there is no syntax like this:

var score: Int

or

var score = 0

I just want to know why, or how to do that, using a variable without declaring its type with var syntax.

As the grammar in C++ (Swift is, in some way, similar with C++), it should be "can't be recognized" if the variable has not been declared.

Thanks in advance.

Upvotes: 4

Views: 369

Answers (1)

Aaron Brager
Aaron Brager

Reputation: 66302

score is assigned by the for loop. Its type is inferred as whatever the element of individualScores is. Since individualScores is an Array of Int, or [Int], score must be an Int. Therefore, you don't need to formally declare its type in this case.

There's similar behavior with closures, where you can name variables without formally declaring them with let or var. For example:

let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0

individualScores.forEach {
    score in
    if score > 50 {
        teamScore += 3
    } else {
        teamScore += 1
    }
}

print(teamScore)

Upvotes: 5

Related Questions