Swift3 如何最小化选项

Swift3 如何最小化选项,swift3,chaining,Swift3,Chaining,我想输入一个数字作为字符串,我正在使用readLine返回一个字符串?。然后我想把输入的字符串转换成一个Int,它也返回一个Int?。如果任意一个选项返回nil,则打印一个错误;否则,使用Int。下面的代码可以工作,但必须有更好的方法。有什么想法吗 print ("Enter number: ", terminator:"") let number = readLine () if number != nil && Int (number!) != nil { let

我想输入一个数字作为字符串,我正在使用readLine返回一个字符串?。然后我想把输入的字符串转换成一个Int,它也返回一个Int?。如果任意一个选项返回nil,则打印一个错误;否则,使用Int。下面的代码可以工作,但必须有更好的方法。有什么想法吗

print ("Enter number: ", terminator:"")
let number = readLine ()

if number != nil && Int (number!) != nil
{
    let anInt = Int (number!)!
}
else
{
    print ("Input Error")
}

您可以将
readLine
响应的展开和到
Int
的转换结合起来,并确保数字转换成功地转换为单个
guard
语句,例如

guard let string = readLine(), let number = Int(string) else {
    print("input error")
    return
}

// use `number`, which is an `Int`, here

如果你想的话,很明显你可以把它转过来:

if let string = readLine(), let number = Int(string) {
    // use `number`, which is an `Int`, here
} else {
    print("input error")
}

您可以将
readLine
响应的展开和到
Int
的转换结合起来,并确保数字转换成功地转换为单个
guard
语句,例如

guard let string = readLine(), let number = Int(string) else {
    print("input error")
    return
}

// use `number`, which is an `Int`, here

如果你想的话,很明显你可以把它转过来:

if let string = readLine(), let number = Int(string) {
    // use `number`, which is an `Int`, here
} else {
    print("input error")
}

另一种方法:
guard let number=readLine().map{Int($0)}else{…
另一种方法:
guard let number=readLine().map{Int($0)}else{…