[英]How can I expand the scope of a variable in Swift
I'm writing a macOS Command Line Tool in Xcode. 我正在用Xcode编写macOS命令行工具。 The variable "num1" keeps returning nil.
变量“ num1”始终返回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. 如前所述,您有两个
num1
变量。 The 2nd one is scoped to just the block of the 2nd if
statement. 第二个范围仅限于第二个
if
语句的块。
You also have an issue that readLine
returns an optional String
, not an Int
. 您还有一个问题,
readLine
返回一个可选的String
,而不是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
. 当然,您现在可能需要将
num1
处理为nil
。
One option is to properly unwrap the value: 一种选择是正确解开值:
if let num = num1 {
print("\(num)")
} else {
print("num1 was nil")
}
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)")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.