As of Swift 2 (Xcode 7), you can pass Swift functions/closures
to parameters taking a C function pointer. From the Xcode 7 release notes:
Native support for C function pointers: C functions that take function
pointer arguments can be called using closures or global functions,
with the restriction that the closure must not capture any of its
local context.
So this compiles and works:
func exceptionHandler(exception : NSException) {
print(exception)
print(exception.callStackSymbols)
}
NSSetUncaughtExceptionHandler(exceptionHandler)
Or with an "inline" closure:
NSSetUncaughtExceptionHandler { exception in
print(exception)
print(exception.callStackSymbols)
}
This does exactly the same as the corresponding Objective-C code:
it catches otherwise uncaught NSException
s.
So this will be caught:
let array = NSArray()
let elem = array.objectAtIndex(99)
NOTE:- It does not catch any Swift 2 errors (from throw
) or Swift runtime errors, so this is not caught:
let arr = [1, 2, 3]
let elem = arr[4]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…