该switch语句还可用于尝试转换为不同的类型:
func checkType(_ value: Any) -> String {
switch value {
// `is` 运算符可用于检查类型
case is Double:
return "value is a Double"
//`as` 运算符将进行转换。你不需要在 `switch` 中使用 `as?`。
case let string as String:
return "value is the string: \(string)"
default:
return "value is something else"
}
}
checkType("Cadena") // "value is the string: Cadena"
checkType(6.28) // "value is a Double"
checkType(UILabel()) // "value is something else"