stored property "text" without initial value prevents synthesized initializers

来源:互联网 发布:mac铁锈红怎么样 编辑:程序博客网 时间:2024/04/30 17:12

swift开发时有可能会遇到这样的错误提示

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

stored property “text” without initial value prevents synthesized initializers

看了下文档,有这样的解释:
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 sections.

意思大概就是class和struct的property必须要在实例化之前赋值。那么解决方案就是要赋值或者把变量声明为optional:

class ARandom{    var number: Int = 0    var text: String?}//orclass ARandom{    var number: Int = 0    var text: String = ""}//orclass ARandom{    var number: Int = 0    var text: String    init(){       text =""    }}
0 0
原创粉丝点击