用開關轉換
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"