0

I’m building an app with Swift 3.0. So I have this code:

if let cofig = ConfigCoreDataController.shared.loadConfig() {
   self.textNumber.text = cofig.numero_centrale
}

If I try to start my application, I have this error:

Fatal error: Unexpectedly found nil while unwrapping an Optional value

the loadConfig method is like this:

func loadConfig() -> Config! {
    let request: NSFetchRequest<Config> = NSFetchRequest(entityName: "Config")
    request.returnsObjectsAsFaults = false

    let urls = self.loadConfigFromFetchRequest(request: request)
    if urls.count > 0
    {
        return urls[0]
    }else{
        return nil
    }

}

now, where is the problem ?

Arasuvel
  • 2,971
  • 1
  • 25
  • 40
bircastri
  • 2,169
  • 13
  • 50
  • 119
  • Your problem is you returning Config as nil when `urls.count == 0`. But you force unwrapping the return value `func loadConfig() -> Config!`. It should be `func loadConfig() -> Config?` – vinothp Mar 08 '18 at 09:57
  • should be : func loadConfig() -> Config? – axunic Mar 08 '18 at 11:09

1 Answers1

0

You should check if 'urls' is Optional with nil value.

func loadConfig() -> Config? {
    let request: NSFetchRequest<Config> = NSFetchRequest(entityName: "Config")
    request.returnsObjectsAsFaults = false

    if let urls = self.loadConfigFromFetchRequest(request: request)
    {
        if urls.count > 0
        {
            return urls[0]
        }else{
            return nil
        }
    }

    return nil
}
Adolfo
  • 1,862
  • 13
  • 19