arowmy init 在 Swift < 2 中工作正常,但在 Swift 2 中我从 Xcode 收到一条错误消息 Call can throw, but it is not marked with 'try' and the error is not handled
在let 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/