将 DataSnapshot 转换为自定义结构对象 - Swift 4

Posted

技术标签:

【中文标题】将 DataSnapshot 转换为自定义结构对象 - Swift 4【英文标题】:Converting DataSnapshot to custom struct object - Swift 4 【发布时间】:2018-10-27 22:19:25 【问题描述】:

所以,在我的项目中,我创建了一个自定义结构:

import Foundation
import Firebase

struct CheckedIn 

    let ref: DatabaseReference?
    let key: String
    let max_cm: String
    let max_in: String
    let weight_kg: Int
    let weight_lb: Int

    init(key: String = "", max_cm: String, max_in: String, weight_kg: Int, weight_lb: Int) 

        self.ref = nil
        self.key = key
        self.max_cm = max_cm
        self.max_in = max_in
        self.weight_kg = weight_kg
        self.weight_lb = weight_lb

    

    init?(snapshot: DataSnapshot) 
        guard
            let value = snapshot.value as? [String: AnyObject],
            let max_cm = value["checked_max_cm"] as? String,
            let max_in = value["checked_max_in"] as? String,
            let weight_kg = value["checked_weight_kg"] as? Int,
            let weight_lb = value["checked_weight_in"] as? Int
        else 
            return nil
        

        self.ref = snapshot.ref as DatabaseReference
        self.key = snapshot.key
        self.max_cm = max_cm
        self.max_in = max_in
        self.weight_kg = weight_kg
        self.weight_lb = weight_lb

    

    func toAnyObject() -> Any 

        return [

            "checked_max_cm": self.max_cm,
            "checked_max_in": self.max_in,
            "checked_weight_kg": self.weight_kg,
            "checked_weight_in": self.weight_lb

        ]
    

这是我的数据库的结构:

我正在尝试使用以下代码在视图控制器中检索一些数据:

ref.queryOrderedByKey().observe(.value)  (snapshot) in

    var newItems: [CheckedIn] = []

    for child in snapshot.children 

        print(child)

        if let snapshot = child as? DataSnapshot, let company = CheckedIn(snapshot: snapshot) 

            newItems.append(company)

        

    

    print(newItems)
    self.companiesCheckedIn = newItems
    self.tableView.reloadData()
    UIViewController.removeSpinner(spinner: sv)


问题是,每当我尝试打开视图控制器(这段代码在 .viewDidLoad 中)时,列表“newItems”都是空的。奇怪的是,当我尝试运行时

打印(子)

打印所有数据,

所以我假设'if let snapshot = child as? DataSnapshot, let company = CarryOn(snapshot: snapshot)' 块没有运行,怎么办?

【问题讨论】:

【参考方案1】:

设法使用解决方法解决了问题:

此代码位于 ViewController 的 viewDidLoad() 方法之前

let ref = Database.database().reference().child("alldata")
var companyName: [String] = []
var maxCm: [String] = []
var maxIn: [String] = []
var weightKg: [Int] = []
var weightLb: [Int] = []

而在viewDidLoad()

override func viewDidLoad() 
    super.viewDidLoad()

    ref.queryOrderedByKey().observeSingleEvent(of: .value)  (snapshot) in

        let snapshotValue = snapshot.value as! [String:[String:AnyObject]]
        let sorted = snapshotValue.sorted()  $0.key.lowercased() < $1.key.lowercased() 

        for (key, _) in sorted 

            let keys = snapshotValue[key]
            let company_name = key
            self.companyName.append(company_name)
            let carry_max_cm = keys?["keyname"] as! String
            self.maxCm.append(carry_max_cm)
            let carry_max_in = keys?["keyname"] as! String
            self.maxIn.append(carry_max_in)
            let carry_weight_kg = keys?["keyname"] as! Int
            self.weightKg.append(carry_weight_kg)
            let carry_weight_lb = keys?["keyname"] as! Int
            self.weightLb.append(carry_weight_lb)

        

        self.tableView.reloadData()

    

let sorted = snapshotValue.sorted() $0.key.lowercased() &lt; $1.key.lowercased()

按字母顺序排列字典

【讨论】:

【参考方案2】:

您的“checked_weight_kg”和“checked_weight_in”是整数类型,但您分配了字符串类型。

你的代码 ->

let weight_kg = value["checked_weight_kg"] as? String,
let weight_lb = value["checked_weight_in"] as? String 

改变->

init?(snapshot: DataSnapshot) 
        guard
            let value = snapshot.value as? [String: AnyObject],
            let max_cm = value["carry_max_cm"] as? String,
            let max_in = value["carry_max_in"] as? String,
            let weight_kg = value["checked_weight_kg"] as? Int,
            let weight_lb = value["checked_weight_in"] as? Int
            else 
                return nil
        

        self.ref = snapshot.ref as DatabaseReference
        self.key = snapshot.key
        self.max_cm = max_cm
        self.max_in = max_in
        self.weight_kg = weight_kg
        self.weight_lb = weight_lb

    

【讨论】:

我已尝试按照您的建议更改我的代码,但结果与以前相同。我已经更新了@Sabbir Ahmed 问题中的代码 它说'不能将'String'类型的值分配给'Int'类型' 哦,您已经可以将类型字符串更改为 int,因此您不需要强制转换 那我现在该怎么办?问题依然存在 我正试图解决这个问题,当我恶魔敲你时

以上是关于将 DataSnapshot 转换为自定义结构对象 - Swift 4的主要内容,如果未能解决你的问题,请参考以下文章

将 JSON 转换为自定义对象时出错

如何将 LinkedHashMap 转换为自定义 java 对象?

Angular-6:将字符串转换为自定义对象的数组

Datagridview如何将选定的行转换为自定义对象

当 minifyEnabled 为 true 时,如何将 JSON 字符串转换为自定义对象?

将 pandas 数据框转换为自定义 JSON 格式(然后转换为 JS 对象)