Connor Neville Connor Neville - 7 months ago 24
Swift Question

Swift 'defer' keyword causes Segmentation Fault

This is occurring on an entirely new Xcode project. The first class I added is a subclass of

, which works fine like this:

class CIHomeView: UIView {
init() {
super.init(frame: CGRectZero)

However, as soon as I add the defer:

class CIHomeView: UIView {
init() {
defer { super.init(frame: CGRectZero) }

I get a segmentation fault compile error. Further, Xcode's syntax highlighting stops working momentarily. Very strange. My understanding is that defer is available as of Swift 2.0, and I am indeed running Swift 2.2.


defer is illegal in an init method. The compiler would like to tell you so, but it's crashing before it can do so.

There is a proposal on the table to fix this in an upcoming iteration of Swift 3, and to allow defer to work in this context, under certain circumstances, as there are good reasons for doing so; but until then, don't do it.

You will certainly never be allowed to call super in your defer, however, as this would totally defeat the rules for the order in which things must be done during initialization. The particular thing you are trying to do is a terrible idea. The compiler knows the rules for initializing in a safe and consistent fashion; listen to the compiler.