[swift-evolution] Proposal: partial initialization before returning nil from an initializer

Félix Cloutier felixcca at yahoo.ca
Thu Dec 17 10:00:56 CST 2015


Hi all,

Initializers can now fail, but objects still need to be fully initialized before you can return `nil` from them. For instance:

	class Foo {
		let bar: Int
		init?(baz: Int) {
			guard baz < 100 else {
				return nil
			}
			self.bar = baz
		}
	}

This trivial example causes the following error: "all stored properties of a class instance must be initialized before returning nil from an initializer".

For integers, that's easy: you can simply set them to zero. However, sometimes, you'd want initialization to fail because the arguments you received don't allow you to properly initialize a member. In these cases, you have to make the fields Optionals (implicitly unwrapped or not) to overcome this.

I remember that Chris said that this is a temporary issue and that it would eventually be fixed. I'm starting this thread because I'd love to have this with or before Swift 3 and I'd like to see who thinks this is big enough of an issue to rival the proposals we already have.

Félix



More information about the swift-evolution mailing list