对象数组追加在Swift上不起作用

时间:2019-04-03 06:20:32

标签: ios arrays swift

我是使用swift进行iOS应用开发的初学者。我正在尝试附加对象数组,但是问题是,尽管接收到的值不是nil,但每次尝试附加时我都会在数组上获得nil值。

我的模型

import Foundation

struct GraphModel {
    var status: String?
    var graphData: GraphData?

    init(dictionary: NSDictionary) {
        self.status = dictionary["status"] as! String
        self.graphData = GraphData.init(dictionary: dictionary["data"] as? NSDictionary ?? [:])
    }
}

struct GraphData {
    var completed_order_count: Int?
    var total_xp: Double?
    var total_cash_owed_to_captain: Double?
    var currency: String?
    var current_balance: Double?
    var execution_time: Double?
    var order_count: OrderCount

    init(dictionary: NSDictionary) {
        self.completed_order_count = dictionary["completed_order_count"] as? Int ?? 0
        self.total_xp = dictionary["total_xp"] as? Double ?? 0.0
        self.total_cash_owed_to_captain = dictionary["total_cash_owed_to_captain"] as? Double ?? 0.0
        self.currency = dictionary["currency"] as? String ?? ""
        self.execution_time = dictionary["execution_time"] as? Double ?? 0.0

        self.order_count = OrderCount.init(dictionary: dictionary["order_count"] as? NSDictionary ?? [:])

    }

}

struct OrderCount {
    var completed_order: Int?
    var earned_amount: Double?
    var dataForGraph: DataForGraph

    init(dictionary: NSDictionary) {
        self.completed_order = dictionary["completed_order"] as? Int ?? 0
        self.earned_amount = dictionary["earned_amount"] as? Double ?? 0.0
        self.dataForGraph = DataForGraph.init(dictionary: dictionary["dataForGraph"] as? NSDictionary ?? [:])
    }
}

struct DataForGraph {

    var graphKeyValueArray: [GraphKeyValue]?


    init(dictionary: NSDictionary) {
        let keys = dictionary.allKeys as? [String]

        keys?.forEach { key in

            let value = dictionary[key] as? Int ?? 0
            let graphKeyValue = GraphKeyValue(key: key, value: value)

            self.graphKeyValueArray?.append(graphKeyValue)


        }
        print(abc)
    }

}

struct GraphKeyValue {

    var key: String
    var value: Int

    init(key: String, value: Int) {
        self.key = key
        self.value = value
    }

}

问题出在DataForGraph中。所有其他代码都运行良好。我有研究,但所有研究都和我一样。在DataForGraph中,仅self.graphKeyValueArray?.append(graphKeyValue)无法正常工作。每次调用时,数组仅显示nil。

0 个答案:

没有答案