3

有没有办法把这个if//梯形图写成switch语句else ifelse

let x: Any = "123"

if let s = x as? String {
    useString(s)
}
else if let i = x as? Int {
    useInt(i)
}
else if let b = x as? Bool {
    useBool(b)
}
else {
    fatalError()
}

这是我的尝试:

switch x {
case let s where s is String:   useString(s)
case let i where i is Int:      useInt(i)
case let b where b is Bool:     useBool(b)
default: fatalError()
}

它成功地选择了正确的路径,但//s仍然是 type 。该检查对施放它们没有任何影响。这迫使我在使用前强制施放。ibAnyisas!

switch有没有办法在一个语句中打开类型并将其绑定到名称?

4

1 回答 1

11

当然,您可以使用条件转换模式 case let x as Type

let x: Any = "123"

switch x {
case let s as String:
    print(s)   //use s
case let i as Int:
    print(i)   //use i
case let b as Bool:
    print(b)   //use b
default:
    fatalError()
}
于 2016-08-16T16:53:36.553 回答