为什么每次我尝试让用户在Swift中输入整数时,为什么Xcode都会让我输入“!”在变量之后

时间:2019-02-09 18:53:56

标签: swift input readline

我正在编写一个代码,我需要获取2个用户输入的整数并输出较小的整数。我不熟悉Swift,每次尝试让用户输入整数时,都会出现此错误“可选类型'String的值?'必须解包为'String'“类型的值。我不明白为什么我总是需要加一个“!”在readLine()之后,但这就是我要做的。

print("Enter the first integer")
let int1 = Int(readLine()!)
print("Enter the second integer")
let int2 = Int(readLine()!)
let small_int = min(int1!, int2!) 
print("The smaller integer is", small_int)

2 个答案:

答案 0 :(得分:0)

您可以在docs中阅读

  

从标准输入中读取的字符串。如果在调用readLine()时已经达到EOF,则结果为nil。

...因此,简化了,readLine(strippingNewline:)始终不必返回值,它也可以返回nil(无值),因此返回类型为String?,这是可选的表示您的常量为Stringnil的类型

如果需要获取非可选值,则可以强制拆开可选值或检查值是否存在,如果存在,请使用可选绑定分配一些非可选常量/变量。您可以对Int初始化程序执行相同的操作,因为并非每个nil都不一定是整数,所以它也可以返回String

print("Enter the first integer")
let input1 = readLine()
print("Enter the second integer")
let input2 = readLine()

if let string1 = input1, let int1 = Int(string1), let string2 = input2, let int2 = Int(string2) {
    let small_int = min(int1, int2)
    print("The smaller integer is", small_int)
} else {
    print("Invalid input")
}

或者您可以使用默认值,因此,如果值是nil,则常量将被赋予给定的默认值

print("Enter the first integer")
let int1 = Int(readLine() ?? "") ?? 0
print("Enter the second integer")
let int2 = Int(readLine() ?? "") ?? 0
let small_int = min(int1, int2) 
print("The smaller integer is", small_int)

答案 1 :(得分:0)

我建议以防御性方式编写代码。这包括处理意外的结果。

readline()Int()都可以返回nil。正如其他答案已经解释的那样,如果您已达到EOF,则readline返回nil。

因此,我的建议是使用??运算符为故障案例提供替代值。例如:let line = readline() ?? “”

或者,尤其是在内部方法中,您可能希望早期使用guard进行纾困,并在方法末尾使用经过验证的输入和非空输入进行实际工作。

请记住,您的示例可以这样重写:

let line = readline() ?? “”
let int1 = Int(line) ?? 0
//...

或作为带有警卫的方法:

func smallerInteger() -> Int? {
   print("Enter the first integer")
   guard let line1 = readline() else {
      return nil
   }
   guard let int1 = Int(line1) else {
      return nil
   }
   print("Enter the second integer")
   guard let line2 = readline() else {
      return nil
   }
   guard let int2 = Int(line2) else {
      return nil
   }
   return min(int1, int2)
}

当然可以通过同时返回一个Int来改善此问题?和一个错误?例如(Int?, Error?)或使用最新的Swift,Result