NSPredicate raises NSException but can't be handled in Swift

The following objc code handles the NSException raised by NSPredicate (the documentation doesn't say anything about NSException)


@try {
   NSPredicate* predicate = [NSPredicate predicateWithFormat:@"incorrect_predicate like" argumentArray:nil];
   NSLog(@"no problem");
}
@catch (NSException* exception) {
   NSLog(@"exception %@", exception);
}


The swift code raises NSException and seems impossible to catch the error


do {
    let predicate = try NSPredicate(format:"a like", argumentArray:[])
} catch {
    // never called
}


How do I fix this problem without writing objc to catch NSException and raises swifth ErrorType?


Should be useful if NSPredicate declaration contains the "throws" clause and correctly handle the NSException


public class NSPredicate : NSObject, NSSecureCoding, NSCoding, NSCopying {
    public init(format predicateFormat: String, argumentArray arguments: [AnyObject]?) throws
...
}

Where are you getting this predicate format string from?

NSPredicate kinda assumes that you’re using format strings that are hard-wired into your app, and thus throwing an NSException when it gets a bad one is reasonable behaviour (in the same way that NSDictionary throws an NSException when you try to insert nil, it’s considered to be a programming error).

Share and Enjoy

Quinn "The Eskimo!"
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

My app contains a visual predicate expression editor and to check errors I create a NSPredicate and check for exception but under swift the apps simply crashes...

Your best option is to write an Objective-C wrapper that catches the exception and returns an error (which will convert to throws in Swift) or an Optional.

NSPredicate raises NSException but can't be handled in Swift
 
 
Q