Reputation: 900
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!
Upvotes: 4
Views: 1453
Reputation: 540075
_
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.
Upvotes: 5