mercredi 6 juillet 2016

how to make an attribute in the following call optional (ie allow nil)


A long time since I have written iOS code but I have the following Model in an iOS app and works great but now we are finding out that detail is optional and we should allow nil values. How would I adjust the initializer to support this? Sorry, I find the optionals a bit difficult to grasp (concept makes sense - executing it is difficult). class Item{ var id:Int var header:String var detail:String init?(dictionary: [String: AnyObject]) { guard let id = dictionary["id"] as? Int, let header = dictionary["header"] as? String, let detail = dictionary["detail"] as? String else { return nil } self.id = id self.header = header self.detail = detail } and creating: var items = [Item]() if let item = Item(dictionary: dictionary) { self.items.append(item) }

Aucun commentaire:

Enregistrer un commentaire