This continues the discussion from https://devforums.apple.com/thread/271101
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, the following code will crash:
// Objective-C - (NSString *)giveMeAString { return nil; } // Swift func thisWillCrash() { let string = someObjectiveCObject.giveMeAString() let length = string.length // crash }
- 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
- @gparker made another interesting suggestion that would also relieve the problem (but need more work from the app developers): "un-annotated declarations are not imported"
- Are any changes in this direction planned for Swift 2.0? At least some compiler switch to enable this behavior?