Swift2 : throwing error from init

Hi dev community,


I am currently test-driving swift2 on a logging library. Good topic to start with, as it can start simple, and end up much more complex.


I am having problems with the init of my objects : I want to be able to create them from a dictionary. But this requires a lot of validation, as dictionaries may be missing some mandatory values, or contain object of a wrong type.

Swift provides a way to declare failable init method, by declaring them with a "?". Nice, but returning nil will not be very informative.

So to provide feedback, I would like to use the error handling model of swift 2, and throw error from the init with some details about what is wrong with the configuration dictionary.


In some cases, it works. But many of my unit tests are crashing, with SIGABRT, and a message in the console : "pointer being freed was not allocated".


Is it a valid construct to use throw in a init ?

If not, I suppose I will have to create an empty object and then update it with the content of the dictionary in another method that can throw.


The project's sources can be found here : https://github.com/jduquennoy/Log4swift.

Testing with Xcode 7 beta 3, your project unit test does not crash. (Needed some fixes in its performance test.)


Have you removed the crashing parts? Or you've been using an older version of Xcode?

I am seeing this behavior in a project as well (Xcode 7 Beta 4).


I have some convenience initializers that throw, in which they call other objects' convenience initializers that may also throw. All of the convenience initializers are defined in extensions.


If some of the child initializers throw, rather than continuing to propagate the error the top level initializer will crash with "pointer being freed was not allocated" (iPad 2) or a EXC_I386_GPFLT (iPad Air) depending on the simulator.


Changing the convenience initializers into static factory methods does not show this behavior.


I haven't been able to make a small sample project that shows this yet, but if I can I'll submit the bug.

Swift2 : throwing error from init
 
 
Q