Re: Swift 2 throws from init()
Re: Swift 2 throws from init()
- Subject: Re: Swift 2 throws from init()
- From: Greg Parker <email@hidden>
- Date: Wed, 01 Jul 2015 17:04:54 -0700
> On Jul 1, 2015, at 4:49 PM, Rick Mann <email@hidden> wrote:
>
> I'm trying to define a Swift wrapper around CGContext. I want to assert that a Context object, if successfully initialized, will always have a valid CGContextRef property. Since at least one of my initializers can fail, I set it up as "throws".
>
> After getting the actual init code to compile, I've run into this: "error: all stored properties of a class instance must be initialized before throwing from an initializer"
>
> I would have thought that if init() throws, there are no guarantees about the state of the object, and thus I would not have to find a way let the CGContext property be optional.
If init() fails, the new object needs to be destroyed cleanly. Swift's strategy for doing this is (1) require the failing initializer to finish initializing all of the fields, then (2) run the ordinary deinit code from that class and any other classes whose init methods have already run.
Objective-C's strategy is to (1) run all -dealloc methods, including those from classes whose init methods have not yet run or only partially run, and then (2) cross your fingers really hard.
> It seems the only way to handle this is with an Optional (or implicitly unwrapped Optional) type?
Implicitly unwrapped optional is a good solution for this. The source code is no more complicated outside init, and if you get something wrong then you will get a runtime error with a useful message.
--
Greg Parker email@hidden Runtime Wrangler
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden