How does a non optional value obtain a nil value?

后端 未结 4 1317
暖寄归人
暖寄归人 2021-02-13 06:18

The Apple documentation TN2151 says this for a possible cause of a EXC_BREAKPOINT / SIGTRAP:

a non-optional type with a nil valu

相关标签:
4条回答
  • 2021-02-13 06:40

    Contrived, but possible:

    class C {}
    
    let x: C? = nil
    let y: C = unsafeBitCast(x, to: C.self)
    
    print(y) // boom
    
    0 讨论(0)
  • 2021-02-13 06:49

    Happens when interoperating with Objective C. An objc-method could be annotated as nonnull, but nothing prevents it from returning nil anyways. The compiler catches only the most obvious cases and even then it only produces warnings (e.g. when you blatently return nil; in a method that is specified as not returning nil.)

    0 讨论(0)
  • 2021-02-13 06:53

    Consider something like this in Objective-C bridged to Swift:

    - (NSObject * _Nonnull)someObject {
        return nil;
    }
    

    The function is annotated as _Nonnull, but will return nil. This bridged as a non-optional object to Swift and will crash.

    0 讨论(0)
  • 2021-02-13 06:56

    I Don't know for sure, but maybe this happens if you force-unwrap (!) an Optional into the Non-Optional variable like this:

    let a : String? = nil
    var x = "hello"
    x = a!
    

    But it's just a guess...

    0 讨论(0)
提交回复
热议问题