[swift-evolution] Improve Swift APIs for NSExpression and NSIncrementalStore
Andrew Tetlaw
andrew at tetlaw.id.au
Mon Jul 11 22:07:24 CDT 2016
Apologies if this has been discussed, I couldn't find any mention in the
list or on https://github.com/apple/swift-3-api-guidelines-review.
The NSIncrementalStore method:
func referenceObjectForObjectID(_ objectID: NSManagedObjectID) ->
AnyObject
Can thrown an exception, but it's not marked as throws. From the
documentation:
"This method raises an NSInvalidArgumentException if the object ID was not
created by the receiving store."
NSExpression has a constantValue property:
var constantValue: AnyObject { get }
that can raise an exception at runtime, but it's not marked as throws. From
the documentation:
'Accessing this property raises an exception if it is not applicable to the
expression."
The NSExpression constantValue property can also return nil at runtime, but
it's return type is AnyObject; not an optional.
If you construct an NSComparisonPredicate with a format string like:
"property == nil"
and you examine the expression returned by predicate.rightExpression. You
can't call expression.constantValue from Swift because it'll crash with
EXC_BAD_ACCESS. You also can't protect against a nil value because the
return type is not optional.
To protect Swift against both of these situations, you have to use
Objective-C wrapper functions. For example to protect against exceptions:
NSException *_Nullable IADCatchObjCException(void (^_Nullable block)())
{
NSException *exception = nil;
@try {
if (block) {
block();
}
} @catch (NSException *e) {
exception = e;
}
return exception;
}
To protect against a surprise nil at runtime:
inline _Nullable id IADMaybeNilValue(_Nullable id value)
{
return value ?: nil;
}
I was hoping this could be improved for the Swift API?
--
Andrew Tetlaw
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160712/a3f4dbbb/attachment.html>
More information about the swift-evolution
mailing list