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:
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:)
:
How can I form a working generic function like this?
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)
}