I receive, always in the same spot in my code, this classic message:
The problem is, the variable is not declared as an optional. This is the corresponding code:
func idealScalebarPositionInPixels() -> Double {
var distance: Double = 0.0
let distanceBetweenViewsCenters = self.mainViewController.measureButton.center.y - self.mainViewController.compassView.center.y
if Device().isPad {
distance = self.mainViewController.compassView.center.y + (distanceBetweenViewsCenters / 4)
distance *= UIScreen.main.scale
} else {
distance = self.mainViewController.compassView.center.y + (distanceBetweenViewsCenters / 2)
distance *= (UIScreen.main.scale / 2)
}
if self.framework.navigating {
distance = distance + 125
}
if Device.current.isPad {
distance = distance - 24
}
return distance
}
I receive the same reports from firebase and Xcode, and I am certain the bug refers to the "distance" variable, which, as you can see, is not an optional. How this can be possible ? thanks a lot for your attention.
Others have mentioned this obliquely, but let me explain the issue clearly:
Swift has a rather nasty type called "implicitly unwrapped optional". It might look like this:
@IBOutlet var measureButton: UIButton!
The exclamation point at the end tells the compiler "make this variable an optional, but always quietly unwrap it when I reference it. I know it'll never be nil. If it is nil, crash even though the offending code looks good."
Think of this as a "crash if nil" type, because that's what it does. By default, Interface Builder sets up outlets as implicitly wrapped optionals. It does have the "advantage" that if you have any broken IBOutlet links, your app immediately crashes when you reference the outlet, so it draws your attention to the broken link and you know to go fix it.
That is almost certainly what's going on here. If you want our help diagnosing the exact error you'll need to post the exact line that is crashing and the exact error message it's giving. You may also have to post a screenshot of your storyboard/nibfile, with the "connections inspector" shown.
As others have said, there are more obscure cases like a didSet
block where your code might be invoked before your view is loaded and the outlets are set, but that's less common than a broken outlet.