对不起,如果这是一个基本的问题,但我正在学习Swift,我不知道如何打开来自readLine()的输入。
例如,我希望
let n: Int = Int(readLine(strippingNewline: true) ?? -1)若要工作,但它不起作用,也不能将-1替换为匹配类型的"-1"。
let n: Int = Int(readLine(strippingNewline: true) ?? "-1")那么,怎样才是“正确”的方法呢?有人能确切地解释一下Swift在打开选项并使用它们作为像Int这样的构造函数的参数时所做的事情吗?
选项的整个概念对我( Python程序员)来说有点陌生;在Python中,您以“贫民区的方式”处理无效的输入,只有在它们发生后才熄灭火:
try:
n = int(input())
except ValueError:
n = None但我认为斯威夫特的范式是不同的。
发布于 2016-11-17 04:50:02
这里有两个选项赛。
首先,readLine(strippingNewline: true)是可选的。如果在接收到nil (EOF)字符之前没有收到输入,它可以返回EOF。它必须在被传递到Int()之前被打开。
其次,Int()是可选的,因为它给出的String可能不是数字的有效字符串表示形式。
不要在Swift中使用-1来表示“无值”。这被称为前哨值,这正是为防止而发明的选项。如何区分-1的意思是“no/无效输入”和“用户的输入是-1”。
下面是我编写这段代码的方法:
guard let userInput = readLine(strippingNewline: true) else {
// If we got to here, readLine(strippingNewLine:) returned nil
fatalError("Received EOF before any input was given")
}
// If we got to here, then userInput is not nil
if let n = Int(userInput) {
// If we got to here, then userInput contained a valid
// String representation of an Int
print("The user entered the Int \(n)")
}
else {
// If we got to here, then userInput did not contain a
// valid String representation of an Int.
print("That is not a valid Int.")
}https://stackoverflow.com/questions/40646887
复制相似问题