Jim*_*ery 39 string switch-statement swift
我在Swift的switch语句中使用字符串时遇到问题.
我有一个字典叫做opts
声明<String, AnyObject>
我有这个代码:
switch opts["type"] {
case "abc":
println("Type is abc")
case "def":
println("Type is def")
default:
println("Type is something else")
}
Run Code Online (Sandbox Code Playgroud)
并在线上case "abc"
,case "def"
我得到以下错误:
Type 'String' does not conform to protocol 'IntervalType'
Run Code Online (Sandbox Code Playgroud)
有人可以向我解释我做错了什么吗?
Ayu*_*oel 63
在switch语句中使用optional时会显示此错误.只需打开变量,一切都应该有效.
switch opts["type"]! {
case "abc":
println("Type is abc")
case "def":
println("Type is def")
default:
println("Type is something else")
}
Run Code Online (Sandbox Code Playgroud)
编辑:如果您不想强制打开可选项,您可以使用guard
.参考:控制流程:提前退出
mik*_*ejd 37
根据Swift语言参考:
Optional类型是一个枚举,有两种情况,None和Some(T),用于表示可能存在或不存在的值.
所以在引擎盖下,可选类型如下所示:
enum Optional<T> {
case None
case Some(T)
}
Run Code Online (Sandbox Code Playgroud)
这意味着您可以在没有强制解包的情况下前往:
switch opts["type"] {
case .Some("A"):
println("Type is A")
case .Some("B"):
println("Type is B")
case .None:
println("Type not found")
default:
println("Type is something else")
}
Run Code Online (Sandbox Code Playgroud)
这可能更安全,因为如果type
在opts
字典中找不到应用程序将不会崩溃.
Kir*_*ins 17
尝试使用:
let str:String = opts["type"] as String
switch str {
case "abc":
println("Type is abc")
case "def":
println("Type is def")
default:
println("Type is something else")
}
Run Code Online (Sandbox Code Playgroud)
Ech*_*lon 13
我在里面有同样的错误信息prepareForSegue()
,我想这是相当常见的.错误信息有点不透明,但这里的答案让我走上正轨.如果有人遇到这个,你不需要任何类型转换,只需在switch语句周围进行条件展开: -
if let segueID = segue.identifier {
switch segueID {
case "MySegueIdentifier":
// prepare for this segue
default:
break
}
}
Run Code Online (Sandbox Code Playgroud)
而不是不安全的力量打开..我发现更容易测试可选案例:
switch opts["type"] {
case "abc"?:
println("Type is abc")
case "def"?:
println("Type is def")
default:
println("Type is something else")
}
Run Code Online (Sandbox Code Playgroud)
(参见案例补充?)