swift - 如何在 Swift 的 switch 语句中捕获选项的值?
问题描述
我有一个函数,我将 a 解析String
为 a Bool
,Double
或者Int
在回退到 a 之前String
。目前我使用这样的 if-else 条件
func parse(stringValue: String) {
if let value = Bool(stringValue) {
// do something with a Bool
print(value)
} else if let value = Int(stringValue) {
// do something with a Int
print("\(stringValue) is Int: \(value)")
} else if let value = Double(stringValue) {
// do something with a Double
print("\(stringValue) is Double: \(value)")
} else {
// do something with a String
print("String: \(stringValue)")
}
}
这没关系,但我个人的偏好是在 Swift 中使用 switch 语句,但我不知道如何在不强制展开的情况下这样做:
func parse(stringValue: String) {
switch stringValue {
case _ where Bool(stringValue) != nil:
let value = Bool(stringValue)!
// do something with Bool
case _ where Int(stringValue) != nil:
let value = Int(stringValue)!
// do something with Int
case _ where Double(stringValue) != nil:
let value = Double(stringValue)!
// do something with Double
default:
// do something with String
}
}
如何捕获结果where
以便我可以在case
范围内使用它?
解决方案
推荐阅读
- openshift - pod 列表的日志
- python - 我想向具有两个特定角色的人发送私人消息
- python - 创建一个函数,计算使用 Python 使用给定分母可以构建多少个真分数
- html - Django VSCode:如何按预期制作 django-html 格式?
- python - 在python中使用正则表达式在字符串列表中查找匹配关键字之后的下一个单词
- python - What is training accuracy and training loss and why we need to compute them?
- discord.py - Discord.py 反应角色命令
- r - R 闪亮的桌子,桌子内有地块
- html - 将表单添加到按钮
- vue.js - Vue - 带有模板 vslots 的错误或设计