Here is the problem: Sometimes you want to test an element that could be
nil. For example, I recently wanted to test if a view controller has a
right bar button item with a given target. This could be done like this:
The problem with this code is, that if there is no right bar button item
the test execution crashes. Let’s make it kind of better:
Uhhg… Now it doesn’t crash but it’s really ugly. Here comes the rescue
with guard:
This is beautiful! Thanks Swift 2.0 and thanks guard! If you enjoyed
this post, then make sure you subscribe to my
feed.
Update: As suggested in the comments by Stephan Michels I changed
XCTAssertFalse() to XCTFail().
Thanks Stephan!
Update 2: David Owens II wrote on
Twitter that you
can get the same behavior without guard when adding
set.continueAfterFailure = false to the setUp(). Thanks
David!