Swift class 将 AnyObject 转换为 NSMutableDictionary 时转换失败

Swift class cast fails while casting AnyObject to NSMutableDictionary

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? 与可选绑定 if let 一起使用,以确保仅在 snapshot.value 是您期望的类型时才继续。 scoreInt.

也是如此

根据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()
            }
        }
    }              
}

我发现了这个错误,它更多地与 FireBase FDataSnapshot 有关,应该检查快照是否为 nil,使用 snapshot.exists()

var fetchEachStory = Firebase(url:"\(self.individualStoryUrl)\(eachStory)")
            // Read data and react to changes
            fetchEachStory.observeEventType(.Value, withBlock: {
                snapshot in
                if snapshot.exists(){
                    let storyDetails = snapshot.value as NSDictionary?
                    let score = storyDetails!["score"] as Int?
                    var thisStory = eachStory
                    if score? > self.minSetScore{
                        self.showStories[thisStory] = storyDetails
                        self.tableView.reloadData()
                    }
                }

            })