I have a custom class which I want to initialise from a JSON object using JSONCodable https://github.com/matthewcheok/JSONCodable
So I have
public var id: String
public var name: String?
public var imageURL: NSURL?
and a failable initialiser which conforms to the JSONCodable protocol
required public init?(JSONDictionary: JSONObject) {
let decoder = JSONDecoder(object: JSONDictionary)
do {
id = try decoder.decode("id")
name = try decoder.decode("name")
if let imageURLString: String = try decoder.decode("image") {
imageURL = NSURL(string: imageURLString)
}
}
catch let error as NSError{
NSLog("\(error.localizedDescription)")
return nil
}
}
I am getting a compiler error on the 'Return nil' statement: All stored properties of a class instance must be initialized before returning nil from an initialiser. Is there a way round this, apart from setting dummy values? One of the properties I want to include is read-only, I really don't want to create a setter just to get round the compiler. I am using a class, not a struct as in the JSONCodable sample code, because I want to subclass. One possibility is to have a non failing initialiser which throws an error, but this wouldn't conform to the JSONCodable protocol. I'm fairly new to Swift, any pointers on how to handle this would be very welcome.