Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stored property "text" without initial value prevents synthesized initializers

I'm learning swift and have came up with the simple code below.

class ARandom{
    var number: Int = 0
    var text: String
}

However, Xcode displays the following Error:

stored property "text" without initial value prevents synthesized initializers

Why is this happening? what is an synthesized initialiser? why "text" without initial value prevents systhesised initialiser? Could someone please kindly explain it to me? THanks in advance for any help!


1 Answers

You have a few options here.

  1. Make text optional.

    var text: String?

  2. Give text a default value

    var text: String = ""

  3. Give text a value in ARandom's initializer

    init() { text = "" }

The reason this happens is your are defining text as a String. It is not optional. Essentially you are saying that it always is a String and never nil.

With your current code if you created a new instance of ARandom, text would have no value - and that is not possible if text is not optional

Apple's docs probably explain it a bit better

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.

like image 130
James Zaghini Avatar answered Sep 09 '25 03:09

James Zaghini