I want a method to return String or Int as in the method below. How to define the * type? Mind, I dont want to return a tuple, just a single value. :beer:
func returnsSomething(key: Bool) -> * {
if key == true {
return "Im a string!"
} else {
return 42
}
}
returnsSomething(true)
There are two options.
First, you can declare your method as returning type Any
, which will allow you to return any type you want.
func returnsSomething(key: Bool) -> Any {
if key {
return "I'm a string"
} else {
return 42
}
}
This will work perfectly fine, but it has the downside that if you use implicit type definitions:
let foo = returnsSomething(true)
Then foo
won't have the type of String
or Int
, but rather Any
, and you're left with optional downcasting.
let foo = returnsSomething(true)
if let bar = foo as? Int {
// use bar as an Int
} else if let bar = foo as? String {
// use bar as a String
}
As a note, you don't actually have to use Any
here. For example, if you wanted to return a UIView
, UIButton
, or UITableView
, you could use UIView
, as the latter two are both subclasses of UIView
.
Second, you can use method overloading:
func returnsSomething() -> String {
return "I'm a string!"
}
func returnsSomething() -> Int {
return 42
}
This works, but now you cannot use implicit typing at all with this method. Notice that the following generates an error:
let foo = returnsSomething()
Ambiguous use of 'returnsSomething'
However, if we're explicit with the type, this is allowed:
let fooString: String = returnsSomething()
let fooInt: Int = returnsSomething()
And the compiler is perfectly satisfied.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.