Current Latitude and Longitude: Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

Hello, I am trying to show my current latitude and longitude, but I keep getting this error:

Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

How do I fix it?

import UIKit
import CoreLocation

class ViewController: UIViewController {

    @IBOutlet weak var longitude: UILabel!
    @IBOutlet weak var latitude: UILabel!
    var locManager = CLLocationManager()
    var currentLocation: CLLocation!
   
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        locManager.requestWhenInUseAuthorization()
        
       

        if
            locManager.authorizationStatus == .authorizedWhenInUse ||
                locManager.authorizationStatus ==  .authorizedAlways
        {
            currentLocation = locManager.location
        }
        
        
        longitude.text! = "\(currentLocation.coordinate.longitude)"
        latitude.text! = "\(currentLocation.coordinate.latitude)"
        
        
    }
    

}

You have the following potential problems in your code:

  • The longitude label could be nil.
  • The latitude label could be nil.
  • The currentLocation property could be nil.

Accessing a nil optional value will crash your app, as you’ve seen.

Some questions.

Is the condition in the if statement true?

What is the value of currentLocation?

Why does currentLocation have type CLLocation! instead of CLLocation?

Are the outlets connected?

The following articles may help you: