class - 将 AnyObject 转换为 NSMutableDictionary 时,Swift 类转换失败

标签 class swift nsmutablearray classcastexception

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/

相关文章:

jquery - 如何获取元素的第n个子元素

ios - Swift:从 Firebase 打印坐标:0,1 - 2,3 而不是 0,1 - 1,2

ios - 从NSMutableDictionary构建NSMutableArray导致NSException

objective-c - 自定义函数内的空数组

c++ - 作为参数传递的类对象,访问自己的私有(private)成员

class - OCaml中具有相似字段的记录

javascript - 在同一页面上多次重复相同的 JS 函数

ios - 协议(protocol)上的关联类型和泛型

ios - 当似乎没有错误时如何处理我的应用程序中的错误

objective-c - NSMutableArray 排序和分组内存优化