swiftenumstype-alias

typealias based on enum


Is it possible to use an enum to create different typealiases?

For instance, this works:

enum MyEnum {
    case one
    case two
}

struct MyType {
    let type: MyEnum 
    let name: String
    
    // lots of other stuff
}

typealias One = MyType
let one = One(type: .one, name: "One")

Is it possible to pass type: .one already in the typealias, something like this (but this doesn't compile):

typealias One = MyType(type = .one)
let one = One(name: "One")

Can I do this?


Solution

  • You can't use a type alias since you want a dynamic solution. One way is to make use of the init method instead.

    Either by creating a custom init for each use case like

    extension MyType {
        init(oneName: String) {
            self.init(type: .one, name: oneName)
        }
    
        // more init methods
    }
    
    let myType = MyType(oneName: "One")
    

    Or you can use an enum where each item represents a way to create an MyType instance.

    enum MyTypeCreator {
        case one(name: String)
        // other use cases 
    }
    
    extension MyType {
        init(_ creator: MyTypeCreator) {
            switch creator {
            case .one(let name):
                self.init(type: .one, name: name)
            //...
            }
        }
    }
    
    let myType = MyType(.one(name: "One"))
    

    Both ways will let you hide any implementation details inside the init and for more control you can make the default init private.