//函数可返回 Any,
//此时调用方通过类型转换还原类型
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))")
//带 "as" 模式的 switch 用于区分类型
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))")