How to specify the type of a function parameter with combined type CustomStringConvertible and RawRepresentable?

718 views Asked by At

I want a generic function that can instantiate object of a few different enum types I have by supplying the enum type and the Int raw-value. These enums are also CustomStringConvertible.

I tried this:

func myFunc(type: CustomStringConvertible.Type & RawRepresentable.Type, rawValue: Int)

which results in 3 errors:

  • Non-protocol, non-class type 'CustomStringConvertible.Type' cannot be used within a protocol-constrained type
  • Non-protocol, non-class type 'RawRepresentable.Type' cannot be used within a protocol-constrained type
  • Protocol 'RawRepresentable' can only be used as a generic constraint because it has Self or associated type requirements

Forgetting about 'CustomStringConvertible` for now, I also tried:

private func myFunc<T: RawRepresentable>(rawValue: Int, skipList: [T]) {
    let thing = T.init(rawValue: rawValue)
}

But, although code completion suggests it, leads to an error about the T.init(rawValue:):

  • Cannot invoke 'init' with an argument list of type '(rawValue: Int)'

How can I form a working generic function like this?

1

There are 1 answers

6
Dávid Pásztor On BEST ANSWER

The issue is that T.RawValue can be something else than Int with your current type constraints. You need to specify that T.RawValue == Int in order to pass your rawValue: Int input parameter to init(rawValue:).

func myFunc<T: RawRepresentable & CustomStringConvertible>(rawValue: Int, skipList: [T]) where T.RawValue == Int {
    let thing = T.init(rawValue: rawValue)
}