ios - 在 Swift (2.0) 中正确处理 NSJSONSerialization(try catch)?

标签 ios swift

arowmy init 在 Swift < 2 中工作正常,但在 Swift 2 中我从 Xcode 收到一条错误消息 Call can throw, but it is not marked with 'try' and the error is not handledlet anyObj = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject] .我想在我的例子中我不能使用 try catch block ,因为此时 super 还没有初始化。 “尝试”需要一个抛出的函数。

这是我的功能:

required init(coder aDecoder : NSCoder)
{
    self.name  = String(stringInterpolationSegment: aDecoder.decodeObjectForKey("name") as! String!)
    self.number = Int(aDecoder.decodeIntegerForKey("number"))
    self.img = String(stringInterpolationSegment: aDecoder.decodeObjectForKey("image") as! String!)
    self.fieldproperties = []

    var tmpArray = [String]()
    tmpArray = aDecoder.decodeObjectForKey("properties") as! [String]


    let c : Int = tmpArray.count
    for var i = 0; i < c; i++
    {
        let data : NSData = tmpArray[i].dataUsingEncoding(NSUTF8StringEncoding)!

         // Xcode(7) give me error: 'CAll can thorw, but it is not marked with 'try' and the error is not handled'
        let anyObj =  NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject]

        let label = anyObj["label"] as AnyObject! as! String
        let value = anyObj["value"] as AnyObject! as! Int
        let uprate = anyObj["uprate"] as AnyObject! as! Int
        let sufix = anyObj["sufix"] as AnyObject! as! String

        let props = Fieldpropertie(label: label, value: value, uprate: uprate, sufix: sufix)
        self.fieldproperties.append(props)
    }
}

Xcode 意味着: let anyObj = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject]

但我不知道根据这个文档在这里做正确的思考https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html

最佳答案

jsonObject 可以throw 错误,所以把它放在do block 中,使用try,和catch 抛出的任何错误。在 Swift 3 中:

do {
    let anyObj = try JSONSerialization.jsonObject(with: data) as! [String: Any]

    let label = anyObj["label"] as! String
    let value = anyObj["value"] as! Int
    let uprate = anyObj["uprate"] as! Int
    let sufix = anyObj["sufix"] as! String

    let props = Fieldpropertie(label: label, value: value, uprate: uprate, sufix: sufix)

    // etc.
} catch {
    print("json error: \(error.localizedDescription)")
}

或者,在 Swift 4 中,您可以通过使 struct 符合 Codable 来简化代码:

struct Fieldpropertie: Codable {
    let label: String
    let value: Int
    let uprate: Int
    let suffix: String
}

然后

do {
    let props = try JSONDecoder().decode(Fieldpropertie.self, from: data)
    // use props here; no manual parsing the properties is needed
} catch {
    print("json error: \(error.localizedDescription)")
}

对于 Swift 2,请参阅 previous revision of this answer .

关于ios - 在 Swift (2.0) 中正确处理 NSJSONSerialization(try catch)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31296545/

相关文章:

ios - 检测 iOS 版本的最佳位置(方法)在哪里?

iOS UIWebView 页面加载可观察性

ios - 一个 View 上的多手势识别器

ios - 如何在 swift 3 开始编辑时为多个 uitextfield 设置边框颜色?

swift - 类型 'String' 的值不符合预期的字典值类型 'AnyObject'

ios - 您如何处理具有非 Apple 帐户系统的应用程序中的自动续订订阅?

ios - PEM编码的椭圆曲线公钥转换iOS

ios - 观察 NSManagedObject 变量上的 didSet

ios - 创建 View Controller

swift - Firebase 删除不再属于查询的子项