1

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.

primulaveris
  • 966
  • 14
  • 20
  • If you have only one property to check (according your design name and imageURL can be `nil` in the class) I would extract `id` before calling the initializer and declare the initializer non-failable. – vadian Dec 22 '15 at 10:18
  • It has to be failable to conform to the JSONCodable protocol. Also this example is just a proof of concept - I have lots of other properties to add. – primulaveris Dec 22 '15 at 10:29
  • In this case you have to assign to all non optional properties a default value for example an empty string for the `id` property – vadian Dec 22 '15 at 10:36

1 Answers1

0

Fixed with the help of this answer: Best practice to implement a failable initializer in Swift (mentioned here https://github.com/matthewcheok/JSONCodable/issues/5)

So now I have

 public var id: String!

id is now implicitly unwrapped so it has a default value of nil.

Community
  • 1
  • 1
primulaveris
  • 966
  • 14
  • 20