存储 属性 非可选的初始化

Stored property initialisation for non optional

我是 swift 的新手。 我从 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 sections.

但是下面的代码 noOfTyres 没有初始化,编译器也没有报错,请解释一下。

class Vehicle
{
    var noOfTyres: Int!
    var engineCapacity: Int

    init()
    {
        engineCapacity = 10
    }

}

如果将此 属性 设为可选,则可以声明存储的 属性 而无需为其分配初始值。 属性 要么有一个值,要么为零。可选的 属性 要么用

声明
var myOptional : Int?

var myOptional : Int!

因此 noOfTyres 没有被初始化,虽然它是一个可选的,目前它被设置为 nil。

更多信息,请阅读Apple documentation

补充信息。 .

中解释了不同类型的可选声明(!和?)

我不确定这是否可以作为答案

文档说,

Implicitly unwrapped optionals are useful when an optional’s value is confirmed to exist immediately after the optional is first defined and can definitely be assumed to exist at every point thereafter.

因此编译器期望它被初始化,肯定包含一个 value.But 如果我们在 运行 时间内访问它而没有值它会崩溃

如果使用可选项作为存储 属性 ,它将有一个 nil 值,对于其他存储属性,需要初始化。

在您的情况下,编译器不会报错,直到您尝试使用该值。因为你有未包装的值(!),它假定它永远不会为 nil 并且尝试访问该值,将会崩溃。

在这种情况下,我会将默认值添加到 属性 noOfTyres

var noOfTyres: Int = 2

或者,您可以在构造函数中添加该值,以确保每次创建对象时都必须设置该值。

class Vehicle
{
    var noOfTyres : Int!
    var engineCapacity :Int

    init(noOfTyres: Int)
    {
        self.noOfTyres = noOfTyres
        engineCapacity=10;
    }

}

请记住,如果它不是可选的,那么您是说 属性 永远不会为零。

另一件事,按照惯例 class 名称必须大写。