Home > Mobile >  Is there a way to create a union types of String literals in Swift?
Is there a way to create a union types of String literals in Swift?

Time:05-04

In TypeScript, a programmer can define types with string literals. The type EventName below defines a type which must be either "start" OR "stop" OR "end". Note, this actually does not have an effect on runtime, which may be different from how types are used in Swift viz dynamic classes.

type EventName = "start" | "stop" | "end";

interface Listenerlike {
    /** Bind a start event listener. */
    on(event : "start", listener : (startObj : StartObjectlike)=>void) : this;
    /** Bind a stop event listener. */
    on(event : "stop", listener : (startObj : StopObjectlike)=>void) : this;
    /** Bind an end event listener. */
    on(event : "end", listener : (startObj : EndObjectlike)=>void): this;
}

In Swift, I'm only aware of doing something similar with enums:

enum Event : String {
    start = "start",
    stop = "stop",
    end = "end"
}

protocol Listenerlike<T>{
    on(event : Event.start, ...);
    on(event : Event.stop, ...);
    on(event : Event.end, ...);
}

Is there a way to do a string literal union in Swift?

CodePudding user response:

If I understood the TS correctly, the Swift counterpart would just be a protocol with 3 functions:

protocol Listener {
    // FIXME: These parameter/type names are horrible
    func onStart(listener: (StartObject) -> Void) -> Self
    func onStop(listener: (StopObject) -> Void) -> Self
    func onEnd(listener: (EndObject) -> Void) -> Self
}

le fin.

CodePudding user response:

No. There is not a way to create a String literal type union in Swift.

  • Related