如何将Firebase数组转换为Swift数组?

时间:2016-07-14 11:04:00

标签: arrays swift firebase tuples firebase-realtime-database

我正在从包含数组的Firebase数据快照中读取数据。 我将这个快照作为[String:AnyObject]转换为变量say fetchedDict。现在我想将sensorValues转换为快速可读的数组。我检查了sensorValues的dynamicType

print(fetchedDict!["sensorValues"].dynamicType)

是可选的 我尝试了两种方法将其转换为数组:

  1. 向NSArray转发它,[Int]但它没有用。
  2. 写了一个在游乐场工作的镜像功能(见最后),但遗憾的是在iOS App中没有。它给了我 无法施放类型的价值' Swift.Array' (0x117a24028)至' Swift.Int'
  3. 有人可以指导我解决这个问题吗?谢谢!

    rootRef!.observeEventType(.Value, withBlock: { (snapshot) in
    
            for child in snapshot.children.allObjects {
                let snap = child as! FIRDataSnapshot
                let fetchedDict = snap.value as? [String: AnyObject]
    })
    

    这是fetchedDict:

    [
        "activityDuration": 15;
        "sensorValues":   (
            5,
            24,
            24,
            13,
            22,
            4,
            42,
            13,
            3,
            4
        );
        "timestamp": 20160713184023;
    ]
    

    镜像功能在iOS应用程序中无效。尝试Any和AnyObject作为参数类型。这段代码可以在游乐场中使用。

    func tupleToArray(sensorValues: Any) -> [Int] {
        let mirror = Mirror(reflecting: sensorValues)
        var arr = [Int]()
        for child in mirror.children{
            let stringedValue = (child.value) as! Int
            arr.append(stringedValue)
        }
        return arr
     }
    

1 个答案:

答案 0 :(得分:4)

你能直接读作NSArray,然后用它制作一个Swift数组吗?

鉴于

array_node
  0: "index 0"
  1: "index 1"
  2: "index 2"

并阅读

    let myRef = self.myRootRef.childByAppendingPath("array_node")
    myRef.observeSingleEventOfType(.Value, withBlock: { snapshot in

        let a = snapshot.value as! NSArray
        print(a)

        let b = (a as Array).filter {$0 is String}

        print(b)
    })

输出

(
    "index 0",
    "index 1",
    "index 2"
)
[index 0, index 1, index 2]