dibi
dibi

Reputation: 3275

Swift function with generic argument type

I'm looking for an easy and convenient way to implement a function that accepts all types that can be casted to strings e.g.: 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.

Upvotes: 4

Views: 228

Answers (1)

Grimxn
Grimxn

Reputation: 22487

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"

Upvotes: 1

Related Questions