Search code examples
swiftxcodeswift-playground

Nil coalescing operator in swift returns a weird result


Could anyone tell me why Xcode's Playground returns nil if I put double question mark instead of single question mark for variable a? Due to overflow result must be 64, not nil.

Swift version 2.2, Xcode version 7.3.1, OS X version 10.11.6

import Cocoa

   var b: Int8
   var c: String? = "128"
   var a: Int8?? = Int8(c!)

   b = 64

   func nilCoalescing() {
      a != nil ? a! : b
   }

   nilCoalescing()

Solution

  • There's a lot going on here:

    1. a overflows, becaue 128 is larger than the maximum value that can be stored in an Int8 (Int8.max = 127), thus it'll return nil.

      This nil, a.k.a. Optional.None is of type Optional<Int8> is not the type specified by the type annotation of a (Int8??, a.k.a. Optional<Optional<Int8>>), so it's wrapped in another optional, becoming Optional.Some(Optional.None), which is now the correct type.

    2. nilCoalescing() doesn't return anything. (Which actually means it returns (), a.k.a. Void)

    3. Don't do this explicit nil check and force unwrap (!): a != nil ? a! : b. Use ?? instead: a ?? b

    What exactly are you trying to do here?