Search code examples
genericsswiftoption-typeinitializer

Initializers as a way of converting to new types in Swift


I have the following type called Maybe:

enum Maybe<T>:{
    case Nothing
    case Something(T)

    init(){
        self = .Nothing
    }

    init(_ something: T){
        self = .Something(something)
    }


}

I was expecting this code to call my second initializer, to convert an Int into a Maybe<NSDate>:

var c : Maybe<NSDate> = NSDate()

No so. How can I make the above code work (as the builtin Optional does)?


Solution

  • You need to call your initializer:

    var c = Maybe(NSDate()) 
    // type of c inferred as Maybe<NSDate>
    

    Swift's Optional type relies on some compiler magic to allow direct assignment to its Some<T> case without explicitly calling an initializer.