Introducing try-catch from Apple Swift 2, with sandbox on web by IBM Bluemix

Apple Swift is a programming language for iOS application development at the beginning. It can be found on Mac’s Xcode.

Now Apple Swift 2 is hosted on IBM Bluemix’s website (http://swiftlang.ng.bluemix.net). The Swift version  is 2.2-dev as of today,

1
Swift version 2.2-dev (LLVM 46be9ff861, Clang 4deb154edc, Swift 778f82939c)
2
Target: x86_64-unknown-linux-gnu

There are many language features introduced in Swift 2. Let’s begin with the elegant try-catch feature from a sample code,

1
/* Basic fibonacci function in swift.
2
   Demostrates func calls and recursion.
3
*/
4
5
func fibonacci(i: Int) throws -> Int  {
6
    if i <= 2 {
7
        return 1
8
    } else {
9
        return **try** fibonacci(i - 1) + fibonacci(i - 2)
10
    }
11
}
12
13
do {
14
  try print(fibonacci(22))
15
  /* do something that doesn't throw in the middle
16
  */
17
  // the keyword reminds you below function will throw
18
  try print(fibonacci(11))
19
} catch {
20
  print("error")
21
}

The function doesn’t really throw any thing but you can see the function calls that throw are prefixed with try.

The evolution speed of Swift language seems a little bit faster than Google’s Go language on this feature.

Share