[swift-evolution] SR-104: Improve Crash-Safety when Importing Objective-C Code Without Nullability Attributes
Fabian Ehrentraud
Fabian.Ehrentraud at willhaben.at
Tue Dec 8 06:09:22 CST 2015
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?
More information about the swift-evolution
mailing list