[swift-evolution] [Idea] Set variables to "_" in two-stage init; remove IUO

Karl razielim at gmail.com
Wed Jun 15 07:22:01 CDT 2016


Say you have the following code. There is a property on MyClass (‘y’) which is derived from other data via an instance method; Two-stage initialisation.

class MySuperClass {
	init() {}
}

class MyClass : MySuperClass {

	let x : Int
	var y : String

	init(x: Int) {

		self.x = x
		super.init()
		y = someInstanceMethod()
	}
}

The code won’t compile because you call super.init before initialising all properties. The way to work-around this so far is to make the type of ‘y’ an implicitly-unwrapped optional. I don’t think it’s very elegant to have to change the type of ‘y’ in this case - it exposes implementation details and implies that the value may sometimes be nil, which is not the case.

What about if we allowed you to explicitly declare that it’s okay for ‘y’ not to be initialised before calling super.init? Perhaps by assigning it to the underscore:

self.x = x
y = _
super.init()
y = someInstanceMethod()

'y' would still effectively work as an implicitly-unwrapped optional - the value would be initialised to nil, and any attempt to use it before it is initialised would be a fatal runtime error as with an IUO. This also means that it couldn’t be a “let” value.

This change wouldn’t give you any additional safety when using two-stage initialisation; it would simply not require you to change the type of the property when doing so.

Thoughts?

Karl


More information about the swift-evolution mailing list