json - Too many optionals making code messy in Swift -


i parsing json, , first time i'm doing on swift. recently, have been avoiding using forced downcasts it's bad practice.

unfortunately, downside code has become lot more messier, in particular case of trying parse json.

this code:

if let dic = try nsjsonserialization.jsonobjectwithdata(currentdata!, options: nsjsonreadingoptions.allowfragments) as? [string: anyobject] {     student["roll"] = dic["roll"] as? int     student["firstname"] = dic["name"]?.componentsseparatedbystring(" ").first     student["lastname"] = dic["name"]?.componentsseparatedbystring(" ").last      var subjects = [[string: anyobject?]]()      if let dicsubs = dic["subs"] as? [anyobject] {         dicsub in dicsubs {             var sub = [string: anyobject?]()              sub["name"] = dicsub["name"] as? string              if let code = dicsub["code"] as? string {                 sub["code"] = int(code)             }             if let theory = dicsub["theory"] as? string {                 sub["theory"] = int(theory)             }             if let prac = dicsub["prac"] as? string {                 sub["prac"] = int(prac)             }              subjects.append(sub)         }     }      student["subjects"] = subjects } 

the output produced littered optionals way, making unusable. have feeling doing wrong, since objective c version of code cleaner , shorter.

is there way make better?

if needed, here's output produced:

[     roll:optional(1234567),   firstname:optional("firstname"),   lastname:optional("lastname"),   subjects:optional(  [       [         "code":optional(123),       "theory":optional(73),       "name":optional(redacted)     ],     [         "code":optional(123),       "theory":optional(76),       "name":optional(redacted)     ],     [         "code":optional(123),       "theory":optional(48),       "name":optional(redacted)     ],     [         "code":optional(123),       "theory":optional(75),       "prac":optional(19),       "name":optional(redacted)     ],     [         "code":optional(123),       "theory":optional(69),       "prac":optional(18),       "name":optional(redacted)     ],     [         "code":optional(123),       "theory":optional(63),       "prac":optional(28),       "name":optional(redacted)     ]   ]  ) ]) 

unwrap optionals (you're doing of them, all):

if let roll = dic["roll"] as? int {     student["roll"] = roll } 

also, initializer int(...) returns optional, have unwrap optional binding:

if let code = dicsub["code"] as? string, let myint = int(code) {     sub["code"] = myint } 

Comments