iosswiftguard-statement

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


Solution

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

    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")
    }