GitXplorerGitXplorer
w

SwiftExceptionBridge

public
2 stars
0 forks
0 issues

Commits

List of commits on branch master.
Unverified
2be35449465a6f12cf40490379f141a3c0bfcb00

BUGFIX: Crash on Potential nil Exception

wweissi committed 10 years ago
Unverified
007a8360db7fdd0dd132e5e829023b5a7aa29dce

BUGFIX: Small Fix to Allow Functions Returning nil

wweissi committed 10 years ago
Unverified
7295c5d46ad89342c866ebf37049a7cc8f335310

DOC: Improved README

wweissi committed 10 years ago
Unverified
83f611e01d2d3cf4686c00ef41423342160d2ffc

DOC: Add README.md

wweissi committed 10 years ago
Unverified
876465f6ff3b9d8b8f1e75e5e1a1b2c23a64905a

MINOR: Enable -fobjc-arc-exceptions

wweissi committed 10 years ago
Unverified
6360db082815ebf35a9fb4b32f7951a7f9830878

first go at demo implementation

wweissi committed 10 years ago

README

The README file for this repository.

SwiftExceptionBridge

Disclaimer

  • I am very happy Swift does not have exceptions, I much rather hope to see a later addition of Computational Expressions or so.
  • I do not want to encourage you to use exceptions.
  • By default exceptions leak memory when combined with ARC (you can use clang -fobjc-arc-exceptions).
  • Unfortunately, there are times when you can't get around catching an exception (NSTask, NSFileHandle, KVO, ...) in Cocoa and currently Swift doesn't allow you to do so.
  • This is a quick prototype not ready for production probably.
  • This repo contains a full Xcode project including all the code (Swift and ObjC).

Proposed Workaround

The following interface

@interface JFWSwiftExceptionBridge : NSObject

+ (void)swiftBridgeTry:(void(^)(void))tryBlock
                except:(void(^)(NSException *))exceptBlock
               finally:(void(^)(void))finallyBlock;

+ (void)swiftBridgeTry:(void(^)(void))tryBlock
                except:(void(^)(NSException *))exceptBlock;

+ (JFWResultOrException *)swiftBridgeResultTry:(id(^)(void))tryBlock;

@end

does allow you to use them from Swift (full swift example). Example:

A full try/catch/finally:

JFWSwiftExceptionBridge.swiftBridgeTry({
    exceptionThrowingFunction()
    },
    except: {
        print("CAUGHT EXCEPTION: \($0)\n")
        },
    finally: {
        () -> Void in
        print("FINALLY\n")
})

Try/catch only:

JFWSwiftExceptionBridge.swiftBridgeTry(exceptionThrowingFunction,
    except: {
        print("CAUGHT EXCEPTION: \($0)\n")
})

Or rather an Either-like type which wraps either the result (type id) as returned from the function or the exception if the function threw an exception:

let roe = JFWSwiftExceptionBridge.swiftBridgeResultTry { () -> AnyObject! in
    return exceptionTrowingFunctionWithResult()
}
print("RESULT OR EXCEPTION: \(roe)\n")

The output then looks either like

RESULT OR EXCEPTION: Result(works)

if it worked and the string "works" was returned, or like that

RESULT OR EXCEPTION: Exception(<DESCRIPTION OF EXCEPTION>)

if an exception appeared.