Using _openExistential to construct a RawRepresentable type

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(_:))
1 Like

Have you managed to figure this out? I was wondering about something similar

Apparently when existentials are unlocked, this will work. I will report back with my findings when that happens.

1 Like

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.

4 Likes

I'll be doing this at runtime with arbitrary protocols, no-can-do

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.

Terms of Service

Privacy Policy

Cookie Policy