I'm looking for an easy and convenient way to implement a function that accepts all types that can be casted to strings eg: myFunc("This string")
or myFunc(2)
or myFunc(true)
. I thought this must be possible with generic parameters and tried something like this:
func myFunc<T: StringLiteralConvertible>(param: T? = nil) -> String {
// ...
return "\(param)"
}
but I had no success so far.
Use CustomStringConvertible
, not StringLiteralConvertible
:
func myFunc<T: CustomStringConvertible>(param: T? = nil) -> String {
// ...
return "\(param)"
}
myFunc("Grimxn") // Optional("Grimxn")
myFunc(12) // Optional(12)
myFunc(true) // Optional(true)
myFunc(-1.234) // Optional(-1.234)
//myFunc() // doesn't work. Compiler can't infer T
These will give Optionals
because you are casting them to T?
to allow your nil
default. Drop the default (it doesn't work anyway - nil
can't imply T
) to get rid of the Optional
.
func myFunc<T: CustomStringConvertible>(param: T) -> String {
// ...
return "\(param)"
}
myFunc("Grimxn") // "Grimxn"
myFunc(12) // "12"
myFunc(true) // "true"
myFunc(-1.234) // "-1.234"
//myFunc((1,2)) // doesn't compile
myFunc(NSDate()) // "2015-10-26 10:44:49 +0000"
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.