Swift: Why Try and Catch don’t work the way you expect

Got a tweet that Swift 2 wasn’t catching array-out-of-bounds exceptions.  Swift’s try/catch aren’t exactly what many devs are used to.  Bounds look-up aren’t “throwing”, so adding try isn’t going to work.

Screen Shot 2015-06-09 at 1.04.55 PM

You can avoid bounds error by using optionals and then test results with if-let.

extension Array {
    subscript (safe index: UInt) -> Element? {
        return Int(index) < count ? self[Int(index)] : nil

But say you want array look-ups to be failing. Right now you can’t create a throwing subscript (radar filed) but you can build a throwing function that provides errors, and that works — in that it fails and you can catch the “out of bounds” failure.

extension Array {
    func lookup(index : UInt) throws -> Element {
        if Int(index) >= count {throw 
            NSError(domain: "com.sadun", code: 0,
                   userInfo: [NSLocalizedFailureReasonErrorKey:
                      "Array index out of bounds"])}
        return self[Int(index)]

do {try [1, 2, 3].lookup(4) // works
   } catch {print(error)}

Comments are closed.