【发布时间】:2016-07-08 14:37:47
【问题描述】:
我要求用户输入(这可行)并尝试输出不同的结果,具体取决于输入是nil、空字符串还是使用switch 子句的非空字符串(不起作用)。
第一次尝试让我出错,因为我正在尝试将可选字符串与非可选字符串进行比较:
import Foundation
print("Hi, please enter a text:")
let userInput = readLine(stripNewline: true)
switch userInput {
case nil, "": // Error: (!) Expression pattern of type ‘String’ cannot match values of type ‘String?’
print("You didn’t enter anything.")
default:
print("You entered: \(userInput)")
}
很公平,所以我创建了一个可选的空字符串来比较:
import Foundation
print("Hi, please enter a text:")
let userInput = readLine(stripNewline: true)
let emptyString: String? = "" // The new optional String
switch userInput {
case nil, emptyString: // Error: (!) Expression pattern of type ‘String?’ cannot match values of type ‘String?’
print("You didn’t enter anything.")
default:
print("You entered: \(userInput)")
}
所以这给了我一个错误,说我无法将“字符串?”与“字符串?”进行比较。
这是为什么呢?它们是否仍然不是同一类型?
PS。我觉得我在这里遗漏了一些基本的东西,例如Troy 指出的关于可选的不是“与相应的非可选类型相同的类型,但有可能没有值”(不是确切的报价,请参阅问题末尾的更新:What does an exclamation mark mean in the Swift language?)。但我一直无法连接最后的点,为什么这不行。
【问题讨论】:
标签: swift switch-statement compare optional