3

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

Marcy
  • 4,611
  • 2
  • 34
  • 52
Drew
  • 674
  • 5
  • 14
  • guard let and if let usage are similar but not same.. You don't have to return in the else block of guard let.. You can check this out. It's very helpful to understand those 2 concepts.. https://stackoverflow.com/questions/32256834/swift-guard-vs-if-let – Said Alır Feb 11 '19 at 21:03
  • 3
    Actually this should fail to compile in a Release build (and does so in my quick test). – Martin R Feb 11 '19 at 21:13

2 Answers2

10

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")
}
CodeBender
  • 35,668
  • 12
  • 125
  • 132
2

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

qtngo
  • 1,594
  • 1
  • 11
  • 13