I need to test if an expression which returns an optional is nil
. This seems like a no-brainer, but here is the code.
if nil != self?.checklists.itemPassingTest({ $0 === note.object }) {
…
}
Which, for some reason, looks unpleasant to my eye.
if let item = self?.checklists.itemPassingTest({ $0 === note.object }) {
…
}
Looks much better to me, but I don't actually need the item, I just need to know if one was returned. So, I used the following.
if let _ = self?.checklists.itemPassingTest({ $0 === note.object }) {
…
}
Am I missing something subtle here? I think if nil != optional …
and if let _ = optional …
are equivalent here.
Update to address some concerns in the answers
I don't see the difference between
nil != var
andvar != nil
, although I generally usevar != nil
. In this case, pushing the!= nil
after the block gets the boolean compare of block mixed in with the boolean compare of the if.The use of the Wildcard Pattern should not be all that surprising or uncommon. They are used in tuples
(x, _) = (10, 20)
, for-in loopsfor _ in 1...5
, case statementscase (_, 0):
, and more (NOTE: these examples were taken from The Swift Programming Language).
This question is about the functional equivalency of the two forms, not about coding style choices. That conversation can be had on programmers.stackexchange.com.
After all this time, Swift 2.0 makes it moot
if self?.checklists.contains({ $0 === note.object }) ?? false {
…
}
See Question&Answers more detail:os