Swift function with a common argument type

I am looking for a simple and convenient way to implement a function that accepts all types that can be written to strings, for example: myFunc("This string")or myFunc(2)or myFunc(true). I thought this should be possible with general parameters and tried something like this:

func myFunc<T: StringLiteralConvertible>(param: T? = nil) -> String {
   // ...
   return "\(param)"
}

but I have not succeeded yet.

+4
source share
1 answer

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

Optionals, T?, nil . ( - nil T), 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"
+1

Source: https://habr.com/ru/post/1613175/


All Articles