将对象添加到对象数组

时间:2018-07-26 08:38:59

标签: ios swift

我有此代码:

struct Calculators
{
    var calculators: [Calculator]?
    var activeCalculator: Int = -1
    var activeSummary: Bool = false
    var activeProfits: Bool = false

public mutating func addCalc(calc: Calculator){
        self.calculators?.append(calc)
    }
}

struct Calculator
{
    var priceSum: Float = 0
    var weightSum: Float = 0
    var pricePerMix: Float = 0

    var pricePerPortion: Decimal?
    var portionDivider: Float?
    var nettoPortionCost: Float?
    var profitPerPortion: Float?
    var pricePerKgAfterPrepare: Float?
    var weightPerPortionInGrams: Float? 
    var concept : PromoConcepts?

    let createTime: Double
    var products : [CountedProduct]?

    init() {
        createTime = NSDate().timeIntervalSince1970 * 1000
    }
}

当我尝试添加新对象时:

var activeCalculators = Calculators()
    let calculator = Calculator()
    activeCalculators.addCalc(calc: calculator)

到对象数组([Calculator]?)。

该应用程序未添加此内容(不起作用)。

有人知道如何解决吗?

5 个答案:

答案 0 :(得分:3)

我猜你忘了创建数组:

null

答案 1 :(得分:1)

您需要像这样初始化它

activeCalculators = [Calculator]()

//

struct Calculators
{
    var calculators = [Calculator]()
    var activeCalculator: Int = -1
    var activeSummary: Bool = false
    var activeProfits: Bool = false

public mutating func addCalc(calc: Calculator){
        self.calculators.append(calc)
    }
}

答案 2 :(得分:1)

struct Calculators
{
    var calculators: [Calculator]?
    var activeCalculator: Int = -1
    var activeSummary: Bool = false
    var activeProfits: Bool = false

    public mutating func addCalc(calc: Calculator){
        if calculators == nil {
             self.calculators = []
        }
        self.calculators?.append(calc)
    }
}

如果您仍然希望将计算器作为可为null的变量,只需在addCalc函数内初始化计算器。 如果这对您来说不是必需的,请寻求Sh_Khan的解决方案

答案 3 :(得分:1)

您的默认初始化方法未创建计算器数组。
所以当你这样初始化的时候
var activeCalculators = Calculators(calculators: nil, ...

add实际上是nil,因此无法完成calculators

您应该像这样初始化它
 var activeCalculators = Calculators(calculators: [Calculator()], ... 或者做一些使其不为零的事情。

答案 4 :(得分:0)

问题是您试图将对象插入未初始化的数组。

您有两个选择:

1。创建和初始化数组

var calculators = [Calculator]()

2。在向其添加对象之前初始化数组。

var activeCalculators = Calculators()
activeCalculators.calculators = [Calculator]()
let calculator = Calculator()
activeCalculators.addCalc(calc: calculator)