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!
You have a few options here.
Make text
optional.
var text: String?
Give text
a default value
var text: String = ""
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With