Decodable
Decodable copied to clipboard
Xcode warning 'no calls to throwing functions occur within 'try' expression with classes
When trying to use Decodable with classes, I get a odd Xcode error no calls to throwing functions occur within 'try' expression
. It's odd because while I can see the line that causes it, Xcode itself doesn't associate the warning with the specific line. And, I don't actually get the error as the init
function does throw.
class Model: NSObject, Decodable {
var name: String
required init(json: AnyObject) throws {
try self.name = json => "name"
}
static func decode(j: AnyObject) throws -> Self {
// Xcode does not like this line
return try self.init(json: j)
}
}

So my questions are:
- Is there a better setup I should be doing when using Decodable with classes?
- Any thoughts on how to resolve that warning itself?
Thanks so much!
Hi!
- I don't think so. I have been doing the same thing, but mostly with final classes.
- Sorry, have no idea why that is happening. Only way I got the error to go away was by doing the following. It might not be the most elegant setup, but I have seriously considered it before for complex init-methods because of the separation of concerns between decoding json values and initializing the object.
class Model: NSObject, Decodable {
var name: String
required init(name: String){
self.name = name
}
static func decode(j: AnyObject) throws -> Self {
return try self.init(name: j => "name")
}
}
And, I don't actually get the error as the init function does throw.
Are you saying it actually doesn't throw? 😮 Then what does it do? Would have been very strange and scary if it acted like try? j =>
, but when I try to replicate it throws like expected.
Also the warning seems to be gone in Swift 3, but I wonder why I didn't see it before.