gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 06:18:49 24 4
gpt4 key购买 nike

我正在从包含数组的 Firebase 数据快照中读取数据。我将这个快照作为 [String: AnyObject] 向下转换为一个变量,比如 fetchedDict。现在我想将传感器值转换为可快速读取的数组。我检查了传感器值的动态类型

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

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

  1. 将其向下转换为 NSArray,[Int] 但没有成功。
  2. 写了一个镜像函数(见最后),它可以在 playground 上运行,但遗憾的是不能在 iOS 应用程序中运行。它给了我Could not cast value of type 'Swift.Array' (0x117a24028) to 'Swift.Int'

有人可以指导我解决这个问题吗?谢谢!

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 作为参数类型。不过这段代码在 playground 中有效。

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
}

最佳答案

你能不能只读入 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]

关于arrays - 如何将 Firebase 数组转换为 Swift 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38372515/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com