John John - 23 days ago 6
Swift Question

How can I expand the scope of a variable in Swift

I'm writing a macOS Command Line Tool in Xcode. The variable "num1" keeps returning nil. I declared it in the beginning so it should be a global variable. How can I address this?

var num1: Int!

if userChoice == "add" {
print("Enter first number")
if let num1 = readLine() {
}
}

print ("\(num1)")

Answer

As mentioned, you have two num1 variables. The 2nd one is scoped to just the block of the 2nd if statement.

You also have an issue that readLine returns an optional String, not an Int.

You probably want code more like this:

var num1: Int?

if userChoice == "add" {
    print("Enter first number")
    if let line = readLine() {
        num1 = Int(line)
    }
}

print ("\(num1)")

Of course you may now need to deal with num1 being nil.

One option is to properly unwrap the value:

if let num = num1 {
    print("\(num)")
} else {
    print("num1 was nil")
}
Comments