fatal error: unexpectedly found nil while unwrapping an Optional value in Swift when tried to parse JSON

前端 未结 3 2157
梦如初夏
梦如初夏 2021-01-25 17:18

I\'ve tried to build up a document-based Cocoa app and when I tried to parse JSON in readFromData: ofType: error: method, I got an error: fatal error: unexpec

3条回答
  •  轮回少年
    2021-01-25 17:54

    • In this case outError is supplied as an argument so you should use it (I overlooked that).
    • Looks like this function's purpose is to check whether data is valid JSON.

    Then your funciton should be:

    override func readFromData(data: NSData?, ofType typeName: String?, error outError: NSErrorPointer) -> Bool {
        if let loadedDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: outError) as? NSDictionary {
           return true
        } else {
           return false
        }
    }
    

    Now this function:

    • write error to where the caller specified in ourError should error occur
    • return wheter the data is valid JSON as NSDictionary

    FYI I happened to write a JSON handler, too.

    • https://github.com/dankogai/swift-json/

    Which includes NSJSONSerialization.JSONObjectWithData.

提交回复
热议问题