自定义类的字典数组

时间:2017-09-29 05:31:40

标签: arrays dictionary firebase swift3 completionhandler

我已成功将Firebase数据提取到字典中,但我很难将值添加到自定义类中。

要从Firebase获取数据,我使用以下代码:

func testing(completion: @escaping ([String : Any]) -> ()) {

    ref.child("dailyJobs").observe(.childAdded, with: { (snapshot) in
        if let value = snapshot.value as? [String : Any] {
            completion(value as [String : Any])
            return
        }
        completion([:])
    })
}

当我调用函数

testing { (dictionary) in
        print(dictionary)
    }

我从Firebase回来的字典就是这个(它是一组字典):

["name": custom chore list, "multiplier": 1, "assigned": none, "order": 0]
["name": bathrooms, "multiplier": 1, "assigned": none, "order": 1]
["name": laundry, "multiplier": 1, "assigned": none, "order": 2]
["name": living room, "multiplier": 1, "assigned": none, "order": 3]
["name": sweep & vacuum, "multiplier": 1, "assigned": sweep & vacuum, "order": 4]
["name": wipe table, "multiplier": 1, "assigned": none, "order": 5]
["name": counters, "multiplier": 1, "assigned": none, "order": 6]
["name": dishes, "multiplier": 1, "assigned": none, "order": 7]
["name": meal prep, "multiplier": 1, "assigned": none, "order": 8]
["name": feed pet / garbage, "multiplier": 1, "assigned": none, "order": 9]

我的自定义类是:

class JobsAndHabits {

var name: String
var multiplier: Double
var assigned: String
var order: Int

init(jobName: String, jobMultiplier: Double, jobAssign: String, jobOrder: Int) {

    self.name = jobName
    self.multiplier = jobMultiplier
    self.assigned = jobAssign
    self.order = jobOrder
}

我解析dictionary的代码是:

testing { (dictionary) in
        for item in dictionary {
            print(item)
            let multiplier = dictionary["multiplier"] as! Double
            let name = dictionary["name"] as! String
            let assigned = dictionary["assigned"] as! String
            let order = dictionary["order"] as! Int

            let dailyJob = JobsAndHabits(jobName: name, jobMultiplier: multiplier, jobAssign: assigned, jobOrder: order)
            self.dailyJobs.append(dailyJob)
        }
        print(self.dailyJobs)

我回来了:

[ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits, ToDo_App.JobsAndHabits]

每个字典中的4个。不知何故,我的代码重复了4倍的数组,现在我的头疼了。我确信有一个简单的解决方案。

我也尝试过:

将所有代码放在原始闭包中,如下所示:

    func loadExistingJobs(_ completion: @escaping () -> ()) {
    ref.child("dailyJobs").observe(.childAdded, with: { (snapshot) in
        if let dictionary = snapshot.value as? [String : Any] {
            let multiplier = dictionary["multiplier"] as! Double
            let name = dictionary["name"] as! String
            let assigned = dictionary["assigned"] as! String
            let order = dictionary["order"] as! Int

            let dailyJob = JobsAndHabits(jobName: name, jobMultiplier: multiplier, jobAssign: assigned, jobOrder: order)
            self.dailyJobs.append(dailyJob)
            self.dailyJobs.sort(by: {$0.order < $1.order})

            self.jobsTableView.reloadData()
            completion()
        }
    })

但是@escaping关闭没有正常运行,我的后续代码也没有被执行。

TL; DR - 我想从Firebase提取数据并将其附加到我的阵列。

2 个答案:

答案 0 :(得分:1)

请检查:

您的dictionary["name": custom chore list, "multiplier": 1, "assigned": none, "order": 0],而您正在为此编写循环。它有4个键,所以它循环4次。

如果你的字典就像[字符串:任意],那么你必须像下面这样打电话:

testing { (dictionary) in
    let multiplier = Double(dictionary["multiplier"] as! Int)
    let name = dictionary["name"] as! String
    let assigned = dictionary["assigned"] as! String
    let order = dictionary["order"] as! Int

    let dailyJob = JobsAndHabits(jobName: name, jobMultiplier: multiplier, jobAssign: assigned, jobOrder: order)
    self.dailyJobs.append(dailyJob)

    print(self.dailyJobs)
})

如果你的字典就像[[String:Any]],那么你必须像下面那样打电话:

func testing(completion: @escaping ([[String : Any]]) -> ()) {
    let dictionary = [[String: Any]]
    ref.child("dailyJobs").observe(.childAdded, with: { (snapshot) in
        for child in (snapshot?.children)! {
            let snap = child as! FDataSnapshot //each child is a snapshot
            if let value = snap.value as? [String : Any] {
                dictionary.append(value)   
            }
        }
        completion(dictionary)
    })
}

testing { (dictionary) in
    for item in dictionary {
        print(item)
        let multiplier = Double(item["multiplier"] as! Int)
        let name = item["name"] as! String
        let assigned = item["assigned"] as! String
        let order = item["order"] as! Int
        let dailyJob = JobsAndHabits(jobName: name, jobMultiplier: multiplier, jobAssign: assigned, jobOrder: order)
        self.dailyJobs.append(dailyJob)
        //            }
        print(self.dailyJobs)
    }
})

答案 1 :(得分:1)

嘿,您可以尝试使用此代码并根据需要进行修改

class JobsAndHabits {

    var name: String
    var multiplier: Double
    var assigned: String
    var order: Int

    init(jobName: String, jobMultiplier: Double, jobAssign: String, jobOrder: Int) {

        self.name = jobName
        self.multiplier = jobMultiplier
        self.assigned = jobAssign
        self.order = jobOrder
    }
    class func getAllJobsAndHabbits(forUserID userID: String, completion: @escaping (JobsAndHabits) -> Swift.Void, failure: @escaping () -> ()) {
        if Auth.auth().currentUser != nil {
            Database.database().reference().child("jobsAndHabits").child(userID).observe(.childAdded, with: { (snapshot) in
                if snapshot.exists() {
                    let receivedMessage = snapshot.value as! [String: Any]

                    let name = receivedMessage["content"] as? String ?? ""
                    let multiplier = receivedMessage["multiplier"] as? Double ?? 0.0
                    let assigned = receivedMessage["assigned"] as? String ?? ""
                    let order = receivedMessage["order"] as? Int ?? 0
                    completion(JobsAndHabits(jobName: name, jobMultiplier: multiplier, jobAssign: assigned, jobOrder: order))
                } else {
                    failure()
                }
            })
        } else {
            failure()
        }
    }
}

致电和处理的方式

class Test {
   let dailyJobs:[JobsAndHabits] = []

   JobsAndHabits.getAllJobsAndHabbits(forUserID: "12346", completion: {
       self.dailyJobs.append(dailyJob)
       self.dailyJobs.sort(by: {$0.order < $1.order})
    }) {
        //handle error
    }
}