[swift-evolution] Proposal: Automatic initializer generation
Kevin Nattinger
swift at nattinger.net
Mon May 23 10:52:42 CDT 2016
Discussed last month https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160411/014890.html
And (linked from that thread) last year http://article.gmane.org/gmane.comp.lang.swift.evolution/727
I think it’s a good idea, but discussion seems to have just petered out without a formal proposal both times.
How about we just apply the struct auto-init behavior to classes? It’s nice and simple, and already in the language.
> On May 23, 2016, at 7:29 AM, Charlie Monroe via swift-evolution <swift-evolution at swift.org> wrote:
>
> A lot of initializers tediously assign values to variables which results in a lot of code such as self.variable = arg1 (or even worse variable = variable), mostly for classes that are meant to just encapsulate several values.
>
> I propose adding auto keyword (to be discussed - anyone has a better name in mind?), which would automatically assign same-named variables. Example:
>
> class User {
> var name: String
> var password: String
>
> init(auto name: String, auto password: String) {
> // No assignment required, the variables will be automatically assigned.
> // Perform additional init stuff here.
> }
> }
>
> This would, of course, work only if the argument has the same name as a stored variable on the class.
>
> Additionally, if the class is root, or the superclass has an initializer that takes no arguments, I propose adding @auto_init annotation, which would generate a default initializer, similar to what is done for structs:
>
> @auto_init
> class User {
> var name: String
> var password: String
> }
>
> Normally, such class would be illegal since it would have no accessible initializers. The annotation could specify the access control as well: @auto_init(private), @auto_init(internal), @auto_init(public).
>
> If the class isn't root, but inherits from an object that has an initializer that takes no arguments (e.g. NSObject), this would be allowed as well and the initializer with no arguments would be called on super.
>
> Any thoughts on this? Sorry, if this has been already discussed.
>
> Charlie
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
More information about the swift-evolution
mailing list