1

In structures, initialization failure is triggered before properties are set to their initial value.

However, in classes a failure is triggered after all properties have been set and delegation has taken place. Why is that?

Why can't both structures and classes trigger initialization failure at the very end of their initialization process?

UPDATE:

Here are the example codes from the Apple Swift documentation:

In the following structure example, initialization failure is triggered before any property is initialized:

struct Animal {
    let species: String
    init?(species: String) {
        if species.isEmpty { return nil }
        self.species = species
    }
}

In the following class example, initialization failure is triggered after properties are set:

class Product {
    let name: String!
    init?(name: String) {
        self.name = name
        if name.isEmpty { return nil }
    }
}

The documentation goes on to state:

For classes, however, a failable initializer can trigger an initialization failure only after all stored properties introduced by that class have been set to an initial value and any initializer delegation has taken place.

Why, in classes, does initialization failure occur ONLY after all properties have been set to their initial value (and delegation taken place)?

Walter M
  • 4,993
  • 5
  • 22
  • 29

1 Answers1

1

As stated by @mustafa in this post:

According to Chris Lattner this is a bug. Here is what he says:

This is an implementation limitation in the swift 1.1 compiler, documented in the release notes. The compiler is currently unable to destroy partially initialized classes in all cases, so it disallows formation of a situation where it would have to. We consider this a bug to be fixed in future releases, not a feature.

Source

Community
  • 1
  • 1
Laffen
  • 2,753
  • 17
  • 29
  • Thank you so much for this! this explains it all. I just wonder why Apple doesn't clarify this in the official documentation, rather than leave readers wondering. smh. – Walter M Jul 28 '15 at 06:29