arowmy初始化工作正常斯威夫特<2,但是在斯威夫特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块,因为此时super尚未初始化。“尝试”需要一个抛出的函数。
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]
这是我的功能:
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]
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块,使用try和catch出现的任何错误。在Swift 3中
jsonObject
throw
do
try
catch
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
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)") }