Skip to content

[SR-120] Objective-C non-null can be bypassed. #42742

@swift-ci

Description

@swift-ci
Previous ID SR-120
Radar None
Original Reporter bnut (JIRA User)
Type Bug
Additional Detail from JIRA
Votes 0
Component/s Compiler
Labels Bug
Assignee None
Priority Medium

md5: 36e04bbfbd87bfb5e14e8fd9005a976e

relates to:

  • SR-8622 Nonnull Objective-C property that falsely returns nil causes inconsistent Swift behavior

Issue Description:

My team finds that we are doing a lot of assertions in methods called from Objective-C that are marked as nonnull because you can still send them nil (from Objective-C). Adding these assertions is not possible in Swift. This report outlines the conditions and a potential solution.

Code to reproduce (Swift 2.1):

func doSomething(thing: MyClass) {
   ...
}
-(void) thisWillFail {
    id thing = nil;
    [instance doSomething: thing];
    [instance doSomethingElse: thing];
}
...
-(void) doSomethingElse: (nonnull MyClass *) thing {
   NSParameterAssert(thing);
   ...
}

This NSParameterAssert can be done in ObjC implementations, but because it's not even an implicitly unwrapped optional that does not work in Swift.

Proposed Solution:

It would be nice to have an assertion implicitly inserted at the caller in Objective-C when the value isn't already annotated as non-null (perhaps: strong reference, argument or object returned from method marked as non-null (compiled with the correct version of swift?)).

Likewise it is possible to cast a Swift type to an unrelated Swift type in Objective-C and pass it back to Swift, perhaps this nullability assertion could be extended to also verify that class or protocol conformance is also correct.

Side-note:

Note, MyClass was defined as follows (using NSString had an empty string rather than a nullptr).

@interface MyClass : NSObject
-(instancetype) init UNAVAILABLE_ATTRIBUTE;
-(instancetype) initWithWhatever:(id) whatever;
@end

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugA deviation from expected or documented behavior. Also: expected but undesirable behavior.compilerThe Swift compiler itself

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions