Reputation: 45
I'm trying to use an or operator to get my function to return "true" if user inputs one of two different answers. With the code below, I keep getting "use of unresolved identifier check2" even though I've initialized check2.
func checkAnswer() {
let check = user.caseInsensitiveCompare(quizbrain.getAnswerText()) == .orderedSame
if quizbrain.getAltText() != nil {
let check2 = user2!.caseInsensitiveCompare(quizbrain.getAltText()!) == .orderedSame
}
else {
check2 = false
}
if check || check2 {
resultLabel.text = "Correct, you answered " + "\"" + user + "\""
print("correct")
}
Upvotes: 1
Views: 158
Reputation: 535159
You need to know about scope. Code can only see a name if it is declared in the same "place". A "place" is (among other things) a matching set of curly braces. Code inside curly braces is invisible outside of those curly braces.
So if we indent properly, we can see the issue:
if quizbrain.getAltText() != nil {
let check2 = // <<---- declaration
} else {
check2 = false // ????
}
if check || check2 { // ???
As you can see, check2
is declared (let
) inside the first set of curly braces. And there it will stay! It cannot leak out of those curly braces. So the other two uses of the word check2
cannot see that let check2
and they do not know that any check2
exists.
But if we move the declaration to a higher scope (and use var
), all is well:
var check2 = false
if quizbrain.getAltText() != nil {
check2 = // ...
}
if check || check2 {
The code inside the first curly braces can see that check2
declaration, because it is further up the scope hierarchy; and so can later code at the same level.
Upvotes: 4