rajesh sukumaran rajesh sukumaran - 5 months ago 14
Swift Question

Stored property initialisation for non optional

I am pretty new to swift .
I found the following document from Apple.

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.

You can set an initial value for a stored property within an
initializer, or by assigning a default property value as part of the
property’s definition. These actions are described in the following

but the below piece of code
is not initialised and the compiler doesn't complain ,please explain this .

class Vehicle
var noOfTyres: Int!
var engineCapacity: Int

engineCapacity = 10



In your case, the compiler won't complain, until you try to use that value. Because you have the value un-wrapped (!) it assumes that it will never be nil and trying to access the value, will crash.

In this case I would add a default value to the property noOfTyres.

var noOfTyres: Int = 2

Or, you can add the value in the constructor to make sure that everytime an object gets created, the value must be set.

class Vehicle
    var noOfTyres : Int!
    var engineCapacity :Int

    init(noOfTyres: Int)
        self.noOfTyres = noOfTyres


Remember, if it's not optional, you are saying, the property will never be nil.

Another thing, by convention class names must be capitalized.