Arowmy init działa dobrze w Swift < 2, ale w Swift 2 dostaję komunikat o błędzie z Xcode Call can throw, but it is not marked with 'try' and the error is not handled
o let anyObj = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject]
. Myślę, że w moim przypadku nie mogę użyć bloku catch catch, ponieważ super nie jest zainicjowany w tym momencie. "Spróbuj" potrzebuje funkcji, która rzuca.Prawidłowa obsługa NSJSONSerialization (try catch) w Swift (2.0)?
tu jest mój funkcji:
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 oznaczać, że: let anyObj = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject]
ale nie mam pojęcia do zrobienia prawo myśleć według tego dokumentu https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html
Proszę przeczytać pełne treści artykułów, a nie tylko części, które uważasz za ważne. Masz już "funkcję, która wyrzuca" - 'NSJSONSerialization.JSONObjectWithData'. –
@Rob tak mam na myśli Swift 2.0. –
Uznano, ponieważ przykładowy kod nie jest użytecznym odniesieniem do poprzednich metod i przykładów. –