Home > Software design >  How to solve generic type issue once we introduce one possible conformation to it in Swift?
How to solve generic type issue once we introduce one possible conformation to it in Swift?

Time:07-31

I am working on this custom function:

func customPrint<T: CustomStringConvertible>(_ value: T...) {
    var string: String = ""
    value.forEach { item in
        string  = " "   String(describing: item)
    }
    print(string)
}

My issue is when I use one type and then use other type! for example this would work fine:

customPrint("hello", "100")

But this would not:

customPrint("hello", 100)

Xcode issue:

Cannot convert value of type 'Int' to expected argument type 'String'

The error is understandable for me, but my goal is to be able use String or Int beside together for feeding my function. So how can i let my generic works for all types that conform to generic? obviously String and Int conforming to CustomStringConvertible, but they cannot get used both together for my function, looking to solve this issue.

Here what i am trying to solve: I am thinking to use type Any like Any... where this Any type can conform to CustomStringConvertible.

CodePudding user response:

Since generics constraint the type of the arguments to be uniform, I would suggest doing something like below:

func customPrint(_ value: CustomStringConvertible...) {
    var string: String = ""
    value.forEach { item in
        string  = " "   String(describing: item)
    }
    print(string)
}

Edit:

Thanks to vacawama, Any would also work with String(describing:):

func customPrint(_ value: Any...) {     
    print(value.map({String(describing: $0)}).joined(separator: " ")) 
}

CodePudding user response:

When you are defining generic type T, you're actually giving the specific type for parameters that you will pass. If you give String parameter first, the function expects all the parameter types as String. If you give Int parameter first, function expects all parameters as Int. You should not use generic in this function. NoeOnJupiter's answer can be usable in your case.

  • Related