将字典数组从Firebase传递到本地数组

时间:2017-03-26 18:44:32

标签: firebase swift3

我正在尝试从Firebase获取一系列字典并传递给本地均衡但是会出现错误的错误。

我的结构示例如下:

struct Places {
var type = ""
var country = ""
var name = ""

init(type: String, country: String, name: String, image: String) {
    self.type = type
    self.country = country
    self.name = name
}

本地数组的地方类型字典

    var allPlaces:[Places] = []

这是我在ViewController上的代码片段

                if let firebasePlaces = snapshot.value as? [String:AnyObject]{

                var localPlace:Places!

                for firebasePlace in firebasePlaces{

                    localPlace?.name = firebasePlace.value["name"] as! String
                    localPlace?.country = firebasePlace.value["country"] as! String
                    localPlace?.type = firebasePlace.value["type"] as! String
                    localPlace?.image = firebasePlace.value["image"] as! String


                    self.allPlaces.append(localPlace)

                }
        }

我在打开一个可选值"时意外地发现了#n; on self.allPlaces.append(localPlace)行。我在上面的例子中缺少什么,有没有人有想法?

1 个答案:

答案 0 :(得分:0)

我通过做一些修改来修复上面的代码。

Places结构应如下所示

struct Places {
var type:String!
var country:String!
var name:String!
var image:String!

init(type: String, country: String, name: String, image: String) {
    self.type = type
    self.country = country
    self.name = name
    self.image = image
}

init(snapshot: FIRDataSnapshot) {

    let snapshotValue = snapshot.value as! [String:AnyObject]

    type = snapshotValue["type"] as! String
    country = snapshotValue["country"] as! String
    name = snapshotValue["name"] as! String
    image = snapshotValue["image"] as! String
}

ViewController上的代码片段

                var plc: [Places] = []
                for eachPlace in (snapshot.children){
                let place = Places(snapshot: eachPlace as! FIRDataSnapshot)
                plc.append(place)
                }

                self.allPlaces = plc