What is new in Swift 2.0

Lots of new feature have been introduced as part of Swift 2.0. The list includes guard, repeat-while, defer, error handling, protocol extensions, print, pattern matching, early exits, UI Testing, UI Stackview etc. Let us see some of these cool features.

guard, try and catch

func printISPDetails() {

    let url = NSURL(string: "http://www.telize.com/geoip")
    let request = NSURLRequest(URL: url!)

    let session = NSURLSession.sharedSession()

    let task = session.dataTaskWithRequest(request) { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
        guard error == nil else {
            print("Error while calling the webservice " + error!.localizedDescription)
            return
        }

        let status = (response as! NSHTTPURLResponse).statusCode

        guard status == 200 else {
            print("Received response status code as \(status)")
            return
        }

        guard data != nil else {
            print("data not received from webservice")
            return
        }
        do {
            let dict = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
            print(dict)
        } catch let error as NSError {
            print("Error parsing JSON response " + error.localizedDescription)
        }
    }
    task.resume()
}

The guard statement is used for checking the else part i.e when there is error print the error and exit the function.

guard error != nil else {
            print("Error while calling the webservice " + error!.localizedDescription)
            return 
        }

Then we have the try catch statments used for parsing the JSON response. Prior to Swift 2.0, JSONObjectWithData method had an extra argument (NSError) for cpaturing the error. Now in Swit 2.0 this is done in cleaner way by throwing an exception when any errors occur while parsing the JSON response. And you can handle this using do, try , catch block as shown below.

	do {
            let dict = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
            print(dict)
        } catch let error as NSError {
            print("Error parsing JSON response " + error.localizedDescription)
        }

defer

if you coming from Java background then defer is simular to finally statement. You can use when you call a piece of code irrespective of success of failure of opertation. One common example would be closing the file handle in a function does a read write operation to a file.

defer { ..code... }

repeat

We all know how do while works, the gets executed for the first time irrespective of codition in the while loop.

var index = 0
do {
    print(index)
    index++
} while (index < 10)

In Swift 2.0, the do keyword is replaced by repeat. Makes more sense right!

var index = 0
repeat {
    print(index)
    index++
} while (index < 10)
In Category: Swift 2

Ravi Shankar

A polyglot software developer and now exploring Swift and iOS development. If you would like to learn from me then check out services page.

Show 0 Comments
No comments yet. Be the first.

Leave a Comment