Uploaded image for project: 'Swift'
  1. Swift
  2. SR-120

Objective-C non-null can be bypassed.

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Open
    • Priority: Medium
    • Resolution: Unresolved
    • Component/s: Compiler
    • Labels:
      None

      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
      

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              bnut Andrew Bennett
              Votes:
              0 Vote for this issue
              Watchers:
              5 Start watching this issue

                Dates

                Created:
                Updated: