简体   繁体   中英

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)")

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")
}
  1. Call the second num1 something else.
  2. Put something in the if.
 var num1: Int!

 if userChoice == "add" {
    print("Enter first number")
    if let num2 = readLine() { 
        // This if-let runs if num2 is not nill. 
        print ("\(num2)")
        num1 = Int(num2)
    }
}

print ("\(num1)")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM