Drew
Drew

Reputation: 739

Using assert in the else block of guard statement

I came across this in the implementation instructions of Google Analytics:

guard let gai = GAI.sharedInstance() else {
    assert(false, "Google Analytics not configured correctly")
}

I had never thought it was possible to have an assertion in the else clause, without returning. This doesn't make sense to me because the assert will only be evaluated in a testing scheme. So, why doesn't the compiler warn about it not returning (in the case of a release build).

Edit: This is within the function application(_:didFinishLaunchingWithOptions) -> Bool

Edit 2: Additional info I found on this that answers it:

Unfortunately, this will break as soon as you do a release build, since assertions are removed in release configurations, and a guard block must end execution of the current scope.

https://help.insight.com/app/answers/detail/a_id/120/~/integrating-google-analytics-into-ios-apps-using-swift-4

Upvotes: 3

Views: 1958

Answers (2)

qtngo
qtngo

Reputation: 1679

In DEBUG, as the assert condition is false, it always stop the program (assertion failed) at this point. So the build success.
In RELEASE, this code's compilation will fail

Upvotes: 2

CodeBender
CodeBender

Reputation: 36610

Typically, a guard statement would use one of the following:

  • return
  • break
  • continue
  • throw

But, you can also use a non-returning function.

This is where fatalError comes into play. You can even create your own custom one with the Never return type.

To the OP point, that will compile in debug, but fail in a release build.

enter image description here

OP could rewrite to the following and have it work:

guard let gai = GAI.sharedInstance() else {
    fatalError("Google Analytics not configured correctly")
}

Upvotes: 10

Related Questions