Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a non optional value obtain a nil value?

Tags:

swift

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

a non-optional type with a nil value

But code such as this won't compile:

var x = "hello"
x = nil

So under what circumstances can a non-optional obtain a nil value?

like image 840
Gruntcakes Avatar asked Jul 21 '17 18:07

Gruntcakes


2 Answers

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.

like image 83
JAL Avatar answered Oct 14 '22 13:10

JAL


Contrived, but possible:

class C {}

let x: C? = nil
let y: C = unsafeBitCast(x, to: C.self)

print(y) // boom
like image 27
Alexander Avatar answered Oct 14 '22 14:10

Alexander