var fetchEachStory = Firebase(url: "\(self.individualStoryUrl)\(eachStory)")
// Read data and react to changes
fetchEachStory.observeEventType(.Value) {
snapshot in
let storyDetails = snapshot.value as NSMutableDictionary?
let score = storyDetails!["score"] as Int?
var thisStory = eachStory
if score? > self.minSetScore {
self.showStories[thisStory] = storyDetails
}
}
将Snapshot.value
分配给故事详细信息时,有时会失败,并显示:
error: Execution was interrupted, reason: EXC_BREAKPOINT (code=EXC_I386_BPT, subcode=0x0).
The process has been returned to the state before expression evaluation.
我该如何处理这个问题?
最佳答案
这行代码:
let storyDetails = snapshot.value as NSMutableDictionary?
如果 snapshot.value
不是 NSMutableDictionary
,则 失败。最好使用条件转换 as?
以及可选绑定(bind) if let
以确保仅在 snapshot.value
为类型时继续你期望的。对于 score
作为 Int
也是如此。
根据the Firebase Documentation :
value
Returns the contents of this data snapshot as native types.
@property (strong, readonly, nonatomic) id value Return Value The data as a native object.
Discussion Returns the contents of this data snapshot as native types.
Data types returned: * NSDictionary * NSArray * NSNumber (also includes booleans) * NSString
Declared In FDataSnapshot.h
所以你应该检查 NSDictionary
而不是 NSMutableDictionary
。
我推荐:
// Read data and react to changes
fetchEachStory.observeEventType(.Value) {
snapshot in
if let storyDetails = snapshot.value as? NSDictionary {
// We know snapshot.value was non-nil and it is an NSDictionary.
if let score = storyDetails["score"] as? Int {
// We know "score" is a valid key in the dictionary and that its
// type is Int.
var thisStory = eachStory
if score > self.minSetScore {
self.showStories[thisStory] = storyDetails
self.tableView.reloadData()
}
}
}
}
关于class - 将 AnyObject 转换为 NSMutableDictionary 时,Swift 类转换失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28261550/