作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在从包含数组的 Firebase 数据快照中读取数据。我将这个快照作为 [String: AnyObject] 向下转换为一个变量,比如 fetchedDict。现在我想将传感器值转换为可快速读取的数组。我检查了传感器值的动态类型
print(fetchedDict!["sensorValues"].dynamicType)
它是可选的
我尝试了两种方法将其转换为数组:
有人可以指导我解决这个问题吗?谢谢!
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/
我是一名优秀的程序员,十分优秀!