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!

3
  • 4
    it means "it is optional and not being interested in what that is". Commented Oct 31, 2018 at 8: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. Commented Oct 31, 2018 at 8: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 _. Commented Oct 31, 2018 at 8:45

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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: Without the question mark “nil < nil” would be true (which is wrong). You can try it with let a: Int? = nil ; print(a < a)
right. I hereby confirm that. thanks @Martin R. well appreciated.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.