Can I use _openExistential to invoke the initializer for an type conforming to a protocol with associated type constrants? Such as ExpressibleByStringLiteral or RawRepresentable.
This doesn't compile:
enum Colors: String {
case red = "red"
case blue = "blue"
case green = "green"
}
func createColor<T: RawRepresentable>(_: T.Type) -> T where T.RawValue == String {
return T.init(rawValue: "red")!
}
let red: Colors = _openExistential(Colors.self, do: createColor(_:))
Bonus: would this also be possible? (Assuming I've asserted inputValue is the correct type, of course)
let inputValue = "red"
func createColor<T: RawRepresentable>(_: T.Type) -> T {
return T.init(rawValue: inputValue as! T.RawValue)!
}
let type: Any.Type = Colors.self
let i = _openExistential(type, do: createColor(_:))
You never need to use _openExistential for an existential with a protocol constraint. Write an extension method on the protocol instead; Self will be the opened type inside the method.
I don't think _openExistential will help you much either, then, because Swift doesn't have any language-level polymorphism over protocols. It can only open the conformances from an existential of a specific known type.