用开关转换
switch
语句也可用于尝试转换为不同的类型:
func checkType(_ value: Any) -> String {
switch value {
// The `is` operator can be used to check a type
case is Double:
return "value is a Double"
// The `as` operator will cast. You do not need to use `as?` in a `switch`.
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"