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

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

This is an example in the Fast 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 you can see, scoreis a variable in the above code section. But he, apparently, was not announced before its use. I mean that there is no such syntax:

var score: Int

or

var score = 0

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

Like a grammar in C ++ (Swift, in some ways, similar to C ++), it should be “cannot be recognized” if the variable was not declared.

Thanks in advance.

+4
source share
1 answer

score for. individualScores. individualScores Array of Int, [Int], score Int. .

, let var. :

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

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

print(teamScore)
+5

Source: https://habr.com/ru/post/1623852/


All Articles