runModal exits with a fatal error.

I have been using this block of Swift code for weeks with no problems. Then, today, every time I invoke it it fails:

let openPanel = NSOpenPanel()
	openPanel.canChooseFiles = true
	openPanel.allowsMultipleSelection = false
	openPanel.canChooseDirectories = true
	openPanel.canCreateDirectories = false
	openPanel.title = NSLocalizedString("Open a CSV file", comment: "Open a CSV File")
	var result = NSApplication.ModalResponse.OK
	do {
		try result = openPanel.runModal()
		}
	catch {
		print("Open Panel failed: \(error)")
		return
		}
	if result == .OK {
		CSVFile = openPanel.url!.path
		}
	else {
		openPanel.close()
		print("No CSV file selected.")
		return
		}

I get this message pointing to the .openModal expression:

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

It's a real head-scratcher!

Answered by DTS Engineer in 883676022

Thanks for the post.

What about using a if let here instead CSVFile = openPanel.url!.path

if let url = openPanel.url {
CSVFile = url.path
}

If the url is nil, will definitely crash! (no exclamation point pun intended)

Hope this helps

Albert Pascual
  Worldwide Developer Relations.

Accepted Answer

Thanks for the post.

What about using a if let here instead CSVFile = openPanel.url!.path

if let url = openPanel.url {
CSVFile = url.path
}

If the url is nil, will definitely crash! (no exclamation point pun intended)

Hope this helps

Albert Pascual
  Worldwide Developer Relations.

Thanks, Albert. That seems to work, although I do not understand why. The error occurs in the "runModal" statement, but your fix in downstream of that. It occurs prior to runModal even opening the OpenPanel on the screen.

@rmc0917 Thanks for the reply, just looking at your code is always a bad idea to force an optional as you have done, I would recommend always to use openPanel.url?.path or better yet the if let to see if there is a value will return.

Happy coding!

Albert Pascual
  Worldwide Developer Relations.

runModal exits with a fatal error.
 
 
Q