4

Few days ago, I converted my old Xcode 8 project to Swift 4 in Xcode 9. I noticed additional Swift codes generated along with explanation just above the code.

Here what it looks like:

// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l < r
  case (nil, _?):
    return true
  default:
    return false
  }
}

I tried to understand what the code does and find what I think is kind of unusual _? in the code.

I guess it is unused optional because _ means we are not going to use a particular variable so we don't care about a variable's name and ? is optional syntax.

Thank you for your help!

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Fitsyu
  • 860
  • 11
  • 19
  • 4
    it means _"it is optional and not being interested in what that is"_. – holex Oct 31 '18 at 08:24
  • 2
    Thinking about it again I am not sure if it is a 100% duplicate. Here `_?` is the *optional* pattern with a wildcard pattern. It matches anything that is not nil. – Martin R Oct 31 '18 at 08:38
  • 1
    I did aware of `_` meaning. But to see it paired with `?` is kinda unusual. Thats what I ask rather than meaning of plain `_`. – Fitsyu Oct 31 '18 at 08:45

1 Answers1

5

_ is the wildcard pattern which matches anything, see for example

And x? is the optional pattern, a shortcut for .some(x), it matches an optional which is not nil.

Here we have the combination of both: _? matches anything that is not nil.

case (nil, _?) matches if the left operand is nil and the right operand is not. You could also write it as case (.none, .some).

Xcode can insert this function during migration from older Swift versions, compare Strange generic function appear in view controller after converting to swift 3.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • I tried to remove `?` from `_?` so it becomes `case (nil, _)` and turns out that the code works the same way as it was with `_?`. So I think the use of `?` here is to emphasize that we deal with optional instead of ordinary variable. CMIW. Thank you. – Fitsyu Oct 31 '18 at 09:30
  • 1
    @fitsyu: Without the question mark “nil < nil” would be true (which is wrong). You can try it with `let a: Int? = nil ; print(a < a)` – Martin R Oct 31 '18 at 09:37
  • right. I hereby confirm that. thanks @Martin R. well appreciated. – Fitsyu Nov 05 '18 at 08:15