Asserting on a throwing expression


(Daryle Walker) #1

I tried using an assert in some code I'm testing:

assert(areEquivalent(tortoiseSecond, hareSecond))

where areEquivalent is a possibly throwing predicate parameter. The compiler complained about the auto-closure being throwing, and there was nowhere for the "try" to go (neither before the "areEquivalent" nor "assert"). I finally did:

assert((try? areEquivalent(tortoiseSecond, hareSecond)) == true)

Is this the best workaround? Should there be some variant of assert that handles this better? (A throw should work either like a false, with possibly a different message, or by re-throwing the error.)


(Xiaodi Wu) #2

Using try! will give you that behavior (i.e., you'll get a runtime trap with a different message).

func f() throws -> Bool {
  return true
}

assert(try! f())