Avoid Swift importing Objective-C as Implicitly Unwrapped by Default
| Originator: | fabian.ehrentraud | ||
| Number: | rdar://21459831 | Date Originated: | 19-Jun-2015 03:34 PM |
| Status: | Open | Resolved: | |
| Product: | Developer Tools | Product Version: | Xcode 7 beta 1 |
| Classification: | Serious Bug | Reproducible: | Always |
Summary:
* In a mixed Swift/Objective-C project, when Objective-C code is brought to Swift as implicitly unwrapped optional by default [1]
* E.g. the Objective-C method signature:
- (NSString *)giveMeAString
will be seen by Swift like this:
func giveMeAString() -> NSString!
* The method giveMeAString might return nil
* As Swift unwraps the method result implicitly, it might crash when `nil` is encountered.
* The bad thing is that the compiler does not give any warnings in this case
* Of course the Objective-C code could be annotated with nullability annotations to avoid these issues, but it is unrealistic to do it at once for a large code base (as also seen for Apple SDKs)
* This issue makes a mixed Swift/Objective-C app much more error prone than a pure Objective-C or a pure Swift app
* To avoid this issue, I would like to suggest changing Swift compiler behavior for importing Objective-C code, assuming `nullable` as default for return types
Steps to Reproduce:
E.g. the following code will crash:
// Objective-C
- (NSString *)giveMeAString { return nil; }
// Swift
func thisWillCrash() {
let string = someObjectiveCObject.giveMeAString()
let length = string.length // crash
}
Expected Results:
The compiler should import Objective-C code as *nullable* by default, if not otherwise annotated.
At least there should be a compiler option to enable that behavior.
Actual Results:
Swift imports Objective-C code as *implicitly unwrapped* by default.
Notes:
Also see original thread in Apple Developer Forums: https://forums.developer.apple.com/message/10042
Comments
Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!
Our response:
Yes, this is still a huge issue for us. If you would add a compiler option to enable this behavior, then it would not have any negative impact by default.
Response from Apple:
This issue behaves as intended.
We considered doing this, but do not believe it produces a usable experience.
We are now closing this bug report.
If you have questions about the resolution, or if this is still a critical issue for you, then please update your bug report with that information.