ios - fatal error :使用JSON文件和SwiftyJSON解开可选值时意外发现nil

标签 ios iphone swift2

我在parseJSON()函数中迅速找到了此代码,它将检索json文件中的Makes,但是我收到一条错误消息,说fatal error: unexpectedly found nil while unwrapping an Optional value
注意:我正在使用SwiftyJSON,错误指向if condition

func parseJSON() {

            let path: String = NSBundle.mainBundle().pathForResource("vehicles", ofType: "json") as String!
            let jsonData = NSData(contentsOfFile: path) as NSData!
            let readableJSON = JSON(data: jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil)
            numberOfRows = readableJSON.count
            for element in 1...numberOfRows {
                var Makes = readableJSON[element]["Make"]

                if !makeArray.contains(Makes.string! && ){ // error is pointing here!
                    let Make = readableJSON[element]["Make"].string as String!
                    makeArray.append(Make)
                }
            }

        }

最佳答案

SwiftyJSON对象的.string属性是可选的getter。

它的值可以存在或为零。

因此,在使用前必须安全地将其拆开。

最简单的例子:

if let makeString = Makes.string {
    if !makeArray.contains(makeString) {
        let Make = readableJSON[element]["Make"].stringValue
        makeArray.append(Make)
    }
}

您可以注意到,使用SwiftyJSON,可选的.string getter的反面是非可选的.stringValue getter。

但是要当心!如果此属性为nil,则应用程序将崩溃。
.stringValue.string!相同

因此,您也可以在此处使用可选的getter和“if let”:
if let makeString = Makes.string {
    if !makeArray.contains(makeString) {
        if let Make = readableJSON[element]["Make"].string {
            makeArray.append(Make)
        } else {
            // readableJSON[element]["Make"].string is nil, handle the error
        }
    }
} else {
    // Makes.string is nil, handle the error
}

等,你明白了。

也可以使用where这样简化:
if let makeString = Makes.string where !makeArray.contains(makeString) {
    if let Make = readableJSON[element]["Make"].string {
        makeArray.append(Make)
    } else {
        // readableJSON[element]["Make"].string is nil, handle the error
    }
} else {
    // Either Makes.string is nil or makeArray does contain it, handle the rror
}

关于ios - fatal error :使用JSON文件和SwiftyJSON解开可选值时意外发现nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35701856/

相关文章:

iphone - 如何在不使用重新加载的情况下隐藏 UITableViewCell 中的重新排序控件?

ios - 解除模态视图 Controller 后未调用委托(delegate)方法

ios - UICollectionView 中单元格之间的零水平间距不起作用

ios - Swift/如何修复 : TableView bottom cells missing in size of the UINavigationBar

iphone - 使用 iPhone 浏览器处理搜索按钮?

Swift, overflow hidden 的文本

ios - 未应用导航栏中标题的描边文本属性

iphone - 在 View IOS 中禁用用户交互

iOS导航返回事件

Swift 添加 : Execution was interrupted, 原因 : EXC_BAD_INSTRUCTION (Code=EXC_l386_INVOP, subcode=0x0)