[swift-evolution] [proposal] Allow convenience initializers to use "self = Foo()"

Braeden Profile jhaezhyr12 at gmail.com
Sun Oct 9 19:07:59 CDT 2016


Not good.  In classes, we can’t always determine the exact type of "self”.  In subclasses of “Me”, such an assignment would not work.  Something like `self = Self(bar: foo)` could work, but that exact case is exactly the same as `self.init(bar: foo)`.

I would still appreciate being able to do this, though, as it could let us do what you want in classes marked “final” (with no subclasses).  It would also be great to be able to use operations and build the class I want to build, then assign it to “self”.

The only problem that becomes apparent here to me is memory management.  At the start of a class’s init, it allocates memory for the instance.  Assigning another instance to “self” would actually change the reference stored in “self”, and the old reference must be deallocated.  Still, I wouldn’t mind such syntax and functionality.

> On Oct 9, 2016, at 3:15 PM, Charles Constant via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Does anyone else think we should allow assignment to self in Class "convenience init" methods?
> 
> Ie: this is legal for a struct, but complains about self being immutable if you try it in a Class, even if it's a convenience init:
> 
>     init( foo:String ){
>         self = Me( bar:foo )
>     }
> 
> I haven't seen this proposed so far, but is there even a reason why can't?
> 
> I've run into headaches with this a couple times lately. Specifically, where the appropriate construct for my code seemed to be an init, but I didn't have access to the desired required init, only a class function. It's also confusing if you decide to change some Type from a struct to a class, to find you have to turn an init into a static function.
> _______________________________________________
> 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