cfischer
cfischer

Reputation: 24902

Default init in Swift enum being ignored

I'm trying to reimplement Optional in Swift. I'm calling it Maybe. I have 2 inits, to create the empty or nil version and the one holding a generic type:

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

    init(){
        self = .Nothing
    }

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

}

However, when I try to create an empty Maybe, the init() initializer is not called. Instead, the other one init(_ something: T) is called with T = ().

What's going on? Why is the init without parameters being ignored?

var z = Maybe() // this calls init(_ something: T) with T = ()

Upvotes: 2

Views: 2282

Answers (1)

Martin R
Martin R

Reputation: 539745

The Swift compiler needs some context to infer the type T, for example

var foo = Maybe<Int>()
var bar : Maybe<String> = Maybe()

The same problem would happen with

let x = Optional()
switch x {
case .None:
    println("None")
case .Some(let y):
    println("Some \(y)")
}

which prints Some () and causes the compiler warning

warning: variable 'x' inferred to have type 'Optional<()>', which may be unexpected

Upvotes: 1

Related Questions