Honey Honey - 4 months ago 10x
Swift Question

How should we initialize stored properties in Structs and Classes?

Apple's documentation states:

Classes and structures must set all of their stored properties to an
appropriate initial value by the time an instance of that class or
structure is created. Stored properties cannot be left in an
indeterminate state.

I have also seen this question, but still wasn't able to find an answer.

// struct

struct FlickrObj { // No Error ????
var title : String
var photographer : String


// class

class FlickrObj { // will create error: Class 'FlickrObj' has no initializers
var title : String
var photographer : String


Apple says both classes and structs must set their stored properties but why doesn't the Struct give any compile time errors?‌


It's because, in the absence of any explicitly declared initializers, the struct itself declares the implicit memberwise initializer init(title:photographer:).

But classes don't do that.

So the class is failing to fulfill the initialization contract (all instance properties must be initialized before the instance itself finishes initializing), but the struct is not failing the contract.