【发布时间】:2015-07-08 15:03:16
【问题描述】:
arowmy init 在 Swift 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 尚未初始化。 “尝试”需要一个抛出的函数。
这是我的功能:
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
【问题讨论】:
-
请阅读全文,而不仅仅是您认为重要的部分。你已经有了一个“抛出的函数”——
NSJSONSerialization.JSONObjectWithData。 -
@Rob 是的,我的意思是 Swift 2.0。
-
投了反对票,因为示例代码对以前的方法和示例没有用处。
-
@NathanMcKasklei 不明白你的意思。该代码描述了我的问题。