[swift-evolution] SR-104: Improve Crash-Safety when Importing Objective-C Code Without Nullability Attributes
Javier Soto
javier.api at gmail.com
Tue Dec 8 09:45:53 CST 2015
I think the decision to import Obj-C APIs with implicitly unwrapped
optionals was a very pragmatic decision at the time. However, given it's
been over a year (I think?) since the nullability specifiers have been
available, I agree with you this could now be improved.
I personally prefer #2: it mimics the old Obj-C behavior ("calling a method
on nil doesn't do anything and any method can take or return nil") if you
use "?." everywhere. This would be somewhat cumbersome, but like you say
would encourage library developers to add these specifiers.
In practice, many developers will work with Apple's frameworks, and Apple
has done a great job tagged all/most of their APIs!
On Tue, Dec 8, 2015 at 4:09 AM Fabian Ehrentraud via swift-evolution <
swift-evolution at swift.org> wrote:
> Swift code accessing Objective-C methods can easily crash - if the
> Objective-C code does not include nullability attributes, the code is
> brought as implicitly unwrapped into Swift, where unsafe accesses do not
> produce compiler warnings.
>
> I created issue SR-104 for this, but as suggested by Jordan Rose it should
> be discussed on this mailing list first.
>
> Short example:
>
> // Objective-C
> - (NSString *)giveMeAString { return nil; }
>
> // Swift
> func thisWillCrash() {
> let string = someObjectiveCObject.giveMeAString()
> let length = string.length // crash
> }
>
> The ClangImporter could handle this issue in several safer ways:
>
> 1. Only import declarations that are nullability annotated (as proposed by
> Greg Parker)
> Positive side effect would be that it would motivate to write nullability
> annotations.
>
> 2. Import un-annotated code as Optional
> Values would need to be unwrapped every time, which does not hurt too much
> due to the easy use of the `?` syntactic sugar.
>
> What do you think? Would this make Swift more safe when used together with
> Objective-C?
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
--
Javier Soto
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151208/7425f848/attachment.html>
More information about the swift-evolution
mailing list