[swift-evolution] Automatic generation of initializer including default values

Guy Miller guyjohnmiller at gmail.com
Mon Oct 10 07:27:15 CDT 2016


Hi,

When I am defining a struct I find myself often using a style as shown in the following example:

struct Foo {

	var greeting: String
	var x: Int
	var y: Int
	var z: Int

	init(greeting: String, x: Int = 1, y: Int = 2, z: Int = 3) {
		self.greeting = greeting
		self.x = x
		self.y = y
		self.z = z
	}
}

This enables one to write code when one doesn’t need to change defaults:

let f = Foo(greeting: “Hello”)

and when one wishes to change one of the defaults:

let f = Foo(greeting: “Hello”, z: 4)

It would be better if one could write the struct in what I understand is the preferred style:

struct Foo {
	var greeting: String
	var x = 1
	var y = 2
	var z = 3
}

and have the compiler generate the initializer:

init(name: String, x: Int = 1, y: Int = 2, z: Int = 3) {
	self.name = name
	self.x = x
	self.y = y
	self.z = z
}

rather than one where all the parameters that have a default value need to be specified in the initializer if one wishes to change just one of them.

Regards,
Guy Miller






More information about the swift-evolution mailing list