[swift-corelibs-dev] NSAttributedString attributesAtIndex return an optional.

Kevin Ballard kevin at sb.org
Tue Dec 8 13:05:13 CST 2015


I agree that precondition is appropriate here. Swift has Optionals and
throws, yes, but Swift also uses preconditions to do things like range
checks on subscripting. I believe the general rule is that if something
is a programmer error, it should be a hard failure (i.e. a
precondition/assert/fatalError), and throws should only be used for
"soft" errors. So subscripting past the end of a collection is a
programmer error, but e.g. trying to decode a non-JSON string as JSON
with NSJSONSerialization is a "soft" error.

Also, as an aside, when an API returns a type that already has a notion
of an empty value (e.g. a Dictionary has [:]), then you should only wrap
it in an Optional if there's a specific reason to differentiate between
an empty value and no value at all. In the case of attributesAtIndex,
I'd expect it to return a non-optional Dictionary, because every valid
index does have a notion of attributes, even if the attribute set is
empty at that location. And passing an invalid index is a programmer
error and should use precondition.

-Kevin Ballard

On Tue, Dec 8, 2015, at 07:59 AM, Philippe Hausler via
swift-corelibs-dev wrote:
> NSException != throw in swift…
> NSExceptions should be treated as assert, fatalError, or precondition
> (precondition in this case is probably preferred)
> 
> 
> > On Dec 8, 2015, at 7:31 AM, James Lee via swift-corelibs-dev <swift-corelibs-dev at swift.org> wrote:
> > 
> > 
> >> 
> >> Personally, if I indexed past the end of an attributed string, I would expect a precondition to fail and (since Swift can't catch assertion failures) my app to crash. (And from what I can tell, the Apple Foundation versions of these APIs do not return an optional.)
> >> 
> >> -- 
> >> Brent Royal-Gordon
> >> Architechies
> >> 
> > 
> > It is worth noting that the current OSX documentation does raise an NSRangeException in the case discussed above. With the throw capabilities in Swift 2 this makes sense.
> > 
> > As you have said, it seems a lot of Foundation API's do not return Optionals. I feel this a hangover from ObjC where an empty object (in this case an NSDictionary) would be returned. To me this is what Optionals are there to replace. 
> > _______________________________________________
> > swift-corelibs-dev mailing list
> > swift-corelibs-dev at swift.org
> > https://lists.swift.org/mailman/listinfo/swift-corelibs-dev
> 
> _______________________________________________
> swift-corelibs-dev mailing list
> swift-corelibs-dev at swift.org
> https://lists.swift.org/mailman/listinfo/swift-corelibs-dev


More information about the swift-corelibs-dev mailing list