如何在新对象中正确声明和添加数据

时间:2018-07-28 19:48:41

标签: swift

我有此代码:

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

    public func getCalculators()-> [Calculator]
    {
        return calculators!
    }
}    

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 products : [CountedProduct]?

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

struct CountedProduct
{
    var productCode: String
    var productCountable: Bool 
    var pricePerKg: Decimal?
    var weightYieldInPercent: Decimal?
    var pieceWeight: Decimal? 
} 

var countedProduct = CountedProduct(productCode: produkt.code!, productCountable: productCountable, pricePerKg: pricePerKg, weightYieldInPercent: weightYieldInPercent, pieceWeight: pieceWeight)

var activeCalculators = Calculators()
var calculatorToAdd = Calculator()
calculatorToAdd.priceSum = 0 
calculatorToAdd.weightSum = 0 //?
calculatorToAdd.pricePerMix = Float(countedProduct.weightAfterPrepareKg as! NSNumber)
calculatorToAdd.pricePerPortion = (countedProduct.costOfTheMixturePerPortion as! NSNumber).decimalValue
calculatorToAdd.portionDivider = 0 //?
calculatorToAdd.nettoPortionCost = Float(countedProduct.costOfTheMixturePerPortion as! NSNumber)
calculatorToAdd.profitPerPortion = Float(countedProduct.overheadOnServing as! NSNumber)
calculatorToAdd.pricePerKgAfterPrepare = Float(countedProduct.pricePerKgAfterPrepare as! NSNumber)
calculatorToAdd.weightPerPortionInGrams = Float(countedProduct.weightAfterPrepareKg as! NSNumber)
calculatorToAdd.products?.append(countedProduct)
calculatorToAdd.products?.append(countedProduct)

我不能更改这些类的形式。 如何正确初始化Calculators对象? 我的产品中有数据。

此代码正确吗?

我想创建一个计算器对象并将其插入到Calculators中。 类别代码无法更改。

1 个答案:

答案 0 :(得分:0)

我认为您可以在代码末尾添加

activeCalculators.calculators = []
activeCalculators.calculators.append(calculatorToAdd)