附加到

时间:2017-09-19 01:26:45

标签: arrays swift

我有两种类型,第一种是Car,其属性为feature,第二种类型为Feature

我有一个属性cars: [Car],当我向其添加新车时,它会返回nil

我在下面的代码段中创建了一个示例:

class Car {
    let make: String
    var features: Feature?
    let id: String

    init(make: String, features: Feature?, id: String) {
        self.make = make
        self.features = features
        self.id = id
    }
}

class Feature {
    let convertible: String

    init(convertible: String) {
        self.convertible = convertible
    }

}

var cars: [Car]?
var feature: Feature?

let featureElement = Feature(convertible: "yes")
feature = featureElement

let car = Car(make: "SomeMaked", features: feature, id: "ID")

cars?.append(car)

print(cars)

我的问题是:数据在添加后不应该增加计数吗?我错过了什么?

请注意,此代码只是示例,因此请忽略拼写错误和编码约定。

1 个答案:

答案 0 :(得分:3)

您尚未初始化阵列。

var cars: [Car]?替换为var cars: [Car]? = []