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 enum
s 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?
The issue is that
T.RawValue
can be something else thanInt
with your current type constraints. You need to specify thatT.RawValue == Int
in order to pass yourrawValue: Int
input parameter toinit(rawValue:)
.