[swift-evolution] [Proposal] Uniform Initialization Syntax

Charles Srstka cocoadev at charlessoft.com
Thu Jun 8 10:00:06 CDT 2017


> On Jun 8, 2017, at 9:19 AM, David Sweeris via swift-evolution <swift-evolution at swift.org> wrote:
> 
> #1 & #3 would violate Swift's rule about having to fully initialize all properties in inits.
> 
> My initial reaction is to like #2, though, assuming I understand it correctly.

Assigning things to self can already be done with structs and enums:

struct S {
	let foo: String
	
	init(foo: String) {
		self.foo = foo
	}
	
	init(bar: String) {
		self = S(foo: bar) // works fine
	}
}

enum E {
	case foo
	case bar
	
	init(isFoo: Bool) {
		if isFoo {
			self = .foo // works fine
		} else {
			self = .bar // ditto
		}
	}
}

The one restriction is that in the case of the struct, you can’t have initialized any of the immutable properties before assigning to self.

struct S {
	let foo: String
	
	init(foo: String) {
		self.foo = foo
	}
	
	init(bar: String) {
		self.foo = "Foo"
		self = S(foo: bar) // error: immutable value 'self.foo' may only be initialized once
	}
}

The only real thing being proposed here, as I see it, is to make this behavior conceptually consistent with classes. Anything that simplifies the rather Byzantine rules surrounding initializers, while simultaneously enabling factory initializers, is a win in my book.

Charles



More information about the swift-evolution mailing list