ios - Try catch whole block in Swift 2 -
i know how make try-catch single function. problem want try-catch whole block of code - simple if goes wrong ignore whole block.
let me show simple example. simple parser facebook graph api /me/taggable_friends:
let params:[nsobject : anyobject] = ["fields": "first_name, last_name, id, picture"] let request = fbsdkgraphrequest(graphpath: "/me/taggable_friends", parameters: params, httpmethod: "get") request.startwithcompletionhandler { (connection, result, error) -> void in if let error = error { print(error) } else{ let resultdictionary:nsdictionary! = result as! [string: anyobject] let array = resultdictionary["data"] as! nsarray object in array { let firstname = object["first_name"] as! string let lastname = object["last_name"] as! string let tagid = object["id"] as! string let picture = object["picture"] as! nsdictionary let picturedata = picture["data"] as! nsdictionary let pictureurl = picturedata["url"] as! string let friend = facebookfriend(firstname: firstname, lastname: lastname, tagid: tagid, picture: pictureurl) print(pictureurl) self.friends.append(friend) } } }
that code working , quietly fail error not nil. let's facebook has changed or somehow values in json aren't available. app crash. have make if-let statements every line of code. it'll make long , hard read. in java i'd make try-catch whole block. in swift don't know how that. what's more compiler saying "as!" (so unwrapping optional value) can't raise exception false :)
this guard
statement comes in handy, basic syntax is:
guard let foo = expression else { handle error, , return (or throw) }
in case, you're wanting protect bunch of optional parsing vagaries of facebook changing api @ point in future. using guard , continue in case allows safely skip rest of block:
object in array { guard let firstname = object["first_name"] as? string, let lastname = object["last_name"] as? string, let tagid = object["id"] as? string, let picture = object["picture"] as? nsdictionary, let picturedata = picture["data"] as? nsdictionary, let pictureurl = picturedata["url"] as? string else { print("json format has changed") continue } let friend = facebookfriend(firstname: firstname, lastname: lastname, tagid: tagid, picture: pictureurl) print(pictureurl) self.friends.append(friend) }
generally speaking, swift try/catch blocks aren't analogous try/catch in other languages, particularly java. in java exceptions (to extent) handleable, such null references, array bounds issues, etc. in swift, try/catch errors definitively not meant handle exceptions, meant handle errors. there's no way use try/catch protect as! string
failing. have expect , protect against possibility, precisely guard comes play, potentially in combination throw.
Comments
Post a Comment