swift - Convenience initializer with non-optional property -


an object of mine has integer id. since required property not defining optional , requiring in designated initializer:

class thing {      var uniqueid: int     var name: string?      init (uniqueid: int) {         self.uniqueid = uniqueid     }         } 

since creating 1 of these json, usage along lines of:

if let uniqueid = dictionary["id"] as? int {     let thing = thing(uniqueid: unique) } 

(i love sanity check on have far way).

next, able add convenience initializer thing class accepts dictionary object , sets properties accordingly. includes required uniqueid , other optional properties. best effort far is:

convenience init (dictionary: [string: anyobject]) {     if let uniqueid = dictionary["id"] as? int {         self.init(uniqueid: uniqueid)         //set other values here?     }         //or here? } 

but of course isn't sufficient since designated initializer isn't called on paths of conditional.

how should handling scenario? possible? or should accept uniqueid must optional?

you have couple of options one. 1 failable initialisers:

convenience init?(dictionary: [string: anyobject]) {     if let uniqueid = dictionary["id"] as? int {         self.init(uniqueid: uniqueid)     } else {         self.init(uniqueid: -1)         return nil     } } 

technically can tweaked bit (mainly depending on preference/version of swift), person preference follows:

class func fromdictionary(dictionary: [string: anyobject]) -> thing? {     if let uniqueid = dictionary["id"] as? int {         return self.init(uniqueid: uniqueid)     }      return nil } 

all together, playground:

class thing {     var uniqueid: int     var name: string?      init(uniqueid: int) {         self.uniqueid = uniqueid     }      convenience init?(dictionary: [string: anyobject]) {         if let uniqueid = dictionary["id"] as? int {             self.init(uniqueid: uniqueid)         } else {             self.init(uniqueid: -1)             return nil         }     }      class func fromdictionary(dictionary: [string: anyobject]) -> thing? {         if let uniqueid = dictionary["id"] as? int {             return self.init(uniqueid: uniqueid)         }          return nil     } }  let firstthing = thing(uniqueid: 1) let secondthing = thing(dictionary: ["id": 2]) let thirdthing = thing(dictionary: ["not_id": 3]) let forththing = thing.fromdictionary(["id": 4]) let fiththing = thing.fromdictionary(["not_id": 4]) 

Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

gradle error "Cannot convert the provided notation to a File or URI" -

python - NameError: name 'subprocess' is not defined -