Joseph Astrahan Joseph Astrahan - 2 months ago 173
JSON Question

Swift 2 to 3 Migration jsonObject produces 'Any' not the expected contextual result type 'AnyObject?'

I'm attempting to convert the following code from this library (https://github.com/dankogai/swift-json) into Swift 3 Compatible code.

I'm stuck on this line though.

obj = try JSONSerialization.jsonObject(


The error I get is jsonObject produces 'Any', not the expected contextual result type 'AnyObject?'

The code before I attempted converting to swift 3 in its full context is below.

public convenience init(data:NSData) {
var err:NSError?
var obj:AnyObject?
do {
obj = try NSJSONSerialization.JSONObjectWithData(
data, options:[])
} catch let error as NSError {
err = error
obj = nil
}
self.init(err != nil ? err! : obj!)
}

Answer

In Swift 3 id types are now imported as Any rather than AnyObject. You can either change the type of obj to Any or cast it to AnyObject.

Comments