【问题标题】:Pattern Matching (Any, Any) as (String, String) Fails in Switch Case模式匹配 (Any, Any) as (String, String) 在 Switch Case 中失败
【发布时间】:2016-01-07 04:21:17
【问题描述】:

在下面的代码中需要帮助。

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

【问题讨论】:

    标签: string swift switch-statement swift2


    【解决方案1】:

    据我所知,你选错了。

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

    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
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2018-09-23
      • 1970-01-01
      • 2017-06-07
      • 2018-04-12
      • 1970-01-01
      • 2017-04-14
      • 1970-01-01
      • 1970-01-01
      • 2020-09-27
      相关资源
      最近更新 更多