-
@stroughtonsmith Back my computer now and did just that. I learned a lot! If a non-optional value returned from Objective-C is null, it will compare as == to
nil
despite the warning. But this isn’t because Swift is doing any sort of manual check to see whether the value is nil. 1/ -
@stroughtonsmith Instead, the
==
seems to be implicitly casting the left hand side to Optional<T> (so you’re comparing Optional<UIApplication> == Optional<UIApplication>), probably by making an Optional.some() wrapping call. But enum instantiation isn’t always implemented as a function call. 2/ -
@stroughtonsmith Instead, Swift computes the total size needed to hold the largest possible associated value for a case in the enum. Then, it tags each enum case (if necessary). (this means that a basic enum with e.g.
case a, b, c
will define a one-byte type with values a→0, b→1, c→2… 3/ -
@stroughtonsmith …) but back to the topic at hand. Swift will encode an enum with one empty case and one case with an associated pointer value (such as Optional’s
none
andsome(Wrapped)
cases, or a similar enum you define yourself) as just the wrapped value in thesome
case, and… 4/ -
@stroughtonsmith …0 in the none case! This means that casting a supposedly non-optional Objective-C value to a Swift Optional (even if you create your own optional type) will correctly produce the nil case when it is really nil. 5/
-
@stroughtonsmith So to still use the
== nil
syntax and suppress the warning, you could writeOptional(UIApplication.shared) == nil
. (theisKind(of:)
check works because it calls into objc which handles the nil correctly). 6/ -
@stroughtonsmith Thanks for posting the tweet that prompted me to figure out how this behavior works and write up this thread! I learned a lot today. 7/7