Search code examples
swiftnulloptional-binding

Print a nil object compiler said "unresolved identifier" What happened behind?


I've tried the following code and I got an error.

var possibleNumber = "Hello World!"

if let actualNumber: Int = Int(possibleNumber) {
    print("\"\(possibleNumber)\" has an integer value of \(actualNumber)")
} else {
    print("\"\(possibleNumber)\" could not be converted to an integer")
}

print(actualNumber) // **Here comes the compile time error**

Error:

use of unresolved identifier 'actualNumber'

What is happening behind the object actualNumber? I declared it in the first part of the optional binding: "if let actualNumber: Int ....." then why is it "unresolved"? hmmm... "unresolved" what is that exactly?

I guess printing a nil is somehow wrong, but why it is wrong? I don't know. Can someone explain this a bit more? and BTW is there a really a nil inside the actualNumber? If so, how can I "see" it?


Solution

  • You are conditionally declaring a variable in an if-statement and want to use it outside the if-statement. This won't work. First of all, you use conditional chaining where you actualNumber only will be initialized of possibleNumber is not nil. If possibleNumber is nil, actualNumber will not exist.

    Secondly, a constant (or variable) declared within an if-statement only has a scope within that if-statement. That means that when you try to access that constant, which you are doing with your last if-statement, the compiler will tell you the constant doesn't exist, "undeclared variable".

    Optional chaining is explained by apple on this site.