Skip to content

Instantly share code, notes, and snippets.

@nilium
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nilium/8369065a7b7801aa79db to your computer and use it in GitHub Desktop.
Save nilium/8369065a7b7801aa79db to your computer and use it in GitHub Desktop.
Exception handling in Swift.
import Foundation
let (succ: String?, err: NSException?) = try {
NSException(name: "ExceptionTest", reason: "Exception reason", userInfo: nil).raise()
return "Foobar"
}
if succ {
println("Success: \(succ)")
} else if err {
println("Error [\(err!.name)]: \(err!.reason)")
}
import Foundation
func try<T>(block: () -> T) -> (T?, NSException?) {
var result: (T?, NSException?) = (nil, nil)
tryWithBlock__({ result = (block(), nil) }, { result = (nil, $0) })
return result
}
#import <Foundation/Foundation.h>
void tryWithBlock__(void (^block)(void), void (^failure)(NSException *));
#import "TryResult.h"
void tryWithBlock__(void (^block)(void), void (^failure)(NSException *)) {
@try {
block();
}
@catch (NSException *exception) {
failure(exception);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment