2

Note the last two lines:

var optionalString: String? // nil
optionalString == "A"       // false
//optionalString! == "A"    // EXC_BAD_INSTRUCTION
optionalString = "A"        // “A”
optionalString == "A"       // true
optionalString! == "A"      // true

Does that mean that we are not required to unwrap an optional when comparing?

sanmai
  • 29,083
  • 12
  • 64
  • 76
  • Compare http://stackoverflow.com/questions/26172911/swift-nil-has-a-numeric-value which is more or less the same question. – Martin R Nov 18 '15 at 08:30
  • 1
    The referenced question is about comparing `x < y` where `x` is an optional `Int?` and `y` is a non-optional `Int`. The given answer applies to `==` as well. – Martin R Nov 18 '15 at 08:34

2 Answers2

2

This is the definition of the == operator that looks like it gets used in this case:

public func ==<T : Equatable>(lhs: T?, rhs: T?) -> Bool

You see that both the first argument (lhs) and the second argument (rhs) have to be of the same type, T?. Since the first argument (optionalString) is String?, I think the second argument is cast to String? too, which makes the comparison work.

I think this proves the idea:

func testCasting<T: Equatable>(a: T?, b: T?) {
    print(a, b) // Optional("A") Optional("A")
}

var optionalString: String? = "A"
testCasting(optionalString, b: "A")

In the second argument you pass a literal A that gets wrapped in an optional to make the types check. The code compiles and runs.

Note that this is completely different from unwrapping the first argument implicitly. That wouldn’t be a safe operation and would undermine the whole point of optionals.

zoul
  • 102,279
  • 44
  • 260
  • 354
0

Apparently one can compare any optional to nil.

optionalString == nil

Which is true if an optional is nil now.

Even this works:

if "A" != nil {
   print("A")
}
sanmai
  • 29,083
  • 12
  • 64
  • 76
  • Related: http://stackoverflow.com/questions/24006975/why-create-implicitly-unwrapped-optionals – sanmai Nov 18 '15 at 09:05
  • Comparing to `nil` should be an obvious feature, since it’s one of the possible valid values of an optional. But note this has nothing to do with implicitly unwrapped optionals. – zoul Nov 18 '15 at 12:47
  • @zoul so that `nil` or `Some(T)` where last always `true`? – sanmai Nov 19 '15 at 04:10
  • Sorry, can’t understand the question, can you rephrase it? – zoul Nov 20 '15 at 11:10