string - 模式匹配 (Any, Any) as (String, String) 在 Switch Case 中失败

标签 string swift switch-statement swift2

在以下代码方面需要帮助。

let first: Any = "One"
let second: Any = "Two"
let values = (first, second)

switch values {
case let (x, y) as (String, String):
    print("Success", x, y)
default:
    print("Failure")
}

switch first {
case let x as String:
   print("Success", x)
default:
   print("Failure")
}

--- 输出

Failure
Success One

--- 预期输出

Success One Two
Success One

演示:http://swiftstub.com/65065637

最佳答案

据我所知,你做错了。

以下是我对您的代码所做的更改,以使其正常工作:

let first: Any = "One"
let second: Any = "Two"
let values = (first, second)

switch values {
case let (x as String, y as String):
    print("Success", x, y)
default:
    print("Failure")
}

switch first {
case let x as String:
    print("Success", x)
default:
    print("Failure")
}

输出:

Success One Two
Success One

希望这对您有所帮助!

关于string - 模式匹配 (Any, Any) as (String, String) 在 Switch Case 中失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34647334/

相关文章:

c# - 如何使用正则表达式查找重复的字符串以及它们之间的值?

c# - String.Equals GID 返回 false?

android - 将字符串从 edittext 传递到新 Intent 会出现错误

swift - Sprite-Kit 开始出现触摸错误

javascript - 如何在switch语句中进行代码优化

java - 如何减少 if 语句

c++ - 为什么 std::string 空代表是这样的?

swift - 如何在 swift re : UIPickerView 中调用用户最近的选择

swift - Cocoa 绘制可 ScrollView 的困境

javascript - Switch 语句和类