//A function may return Any - and then the caller
//restores the type by a cast
func parse(_ text: String) -> Any {
if let number = Int(text) {
return number
}
return text
}
let first = parse("42")
//first is 42
print("first is \(first)")
//type is Int
print("type is \(type(of: first))")
let second = parse("text")
//type is String
print("type is \(type(of: second))")
//A switch with "as" patterns sorts the type out
func show(_ value: Any) -> String {
switch value {
case let number as Int:
return "Int \(number)"
case let text as String:
return "String \(text)"
default:
return "something else"
}
}
//shown is "Int 42"
print("shown is \(show(first))")
//shown is "String text"
print("shown is \(show(second))")