Single integer as key in firebase (Firebase array behavior)

前端 未结 4 1210
粉色の甜心
粉色の甜心 2021-02-10 21:58

If I insert data into node/a/0 in firebase.

the result will treat a is an array a[0].

The same way, if I set my data in

4条回答
  •  不知归路
    2021-02-10 22:36

    I've encountered the same problem, but actually wanted to have a numeric key array in Swift ([Int:AnyObject]). I've written this function to make sure to always have an array (without null values):

    func forceArray(from: Any?) -> [Int:AnyObject] {        
        var returnArray = [Int:AnyObject]()
    
        if let array = from as? [String:AnyObject] {
            for (key, value) in array {
                if let key = Int(key) {
                    returnArray[key] = value
                }
            }
            return returnArray
        }
    
        if let array = from as? [AnyObject] {
            for (key, value) in array.enumerated() {
                if !(value is NSNull) {
                    returnArray[key] = value
                }
            }
            return returnArray
        }
    
        return returnArray
    }
    

    Result:

    ["0":1, "1":2] becomes: [0:1, 1:2]

    {"0":1, "6":2} becomes: [0:1, 6:2]

    ["0":1, "1": null, "2":2] becomes: [0:1, 2:2]

    Hope this is helpful for someone!

提交回复
热议问题