Eli*_*olm 1 compare switch-statement optional swift
我要求用户输入(这工作)并尝试输出不同的结果取决于输入是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)")
}
Run Code Online (Sandbox Code Playgroud)
很公平,所以我创建一个可选的空字符串来比较:
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)")
}
Run Code Online (Sandbox Code Playgroud)
所以这给我一个错误,说我无法比较'字符串?' 到'字符串?'.
这是为什么?他们在某种程度上仍然不是同一类型?
PS.我觉得我在这里缺少一些基本的东西,比如特洛伊指出的选项不是"与相应的非otpional类型相同的类型,但有额外的可能性没有价值"(不是确切的引用) ,在问题的最后看到他的更新:Swift语言中的感叹号是什么意思?).但我仍然坚持连接最后的点,为什么这不好.
更换
case `nil`, "":
Run Code Online (Sandbox Code Playgroud)
同
case nil, .Some(""):
Run Code Online (Sandbox Code Playgroud)
请注意,optional是一个包含两个可能值的枚举:.None和.Some(value).
至于你的第二个例子String?,请注意匹配case是使用~=未定义为选项的运算符执行的.
如果你定义:
@warn_unused_result
public func ~=<T: Equatable>(lhs: T?, rhs: T?) -> Bool {
return lhs == rhs
}
Run Code Online (Sandbox Code Playgroud)
你的例子都会开始工作(不推荐).
| 归档时间: |
|
| 查看次数: |
1666 次 |
| 最近记录: |