0

I am getting this error and I for the life of me cannot figure out why it is returning a nil value.

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

The error is occurring at:

} else {
    gameInfo.player = players
    self.performSegue(withIdentifier: "ServerView", sender: self)
}

Here is my full set of code below starting with the table view controller.

class PlayerSelectViewController: UIViewController {

    @IBOutlet weak var playerButton: UIButton!
    @IBOutlet weak var playersTextBox: UITextField!

    var gameInfo:GameInfo!
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func cancelBtnClicked(_ sender: Any) {
        self.navigationController?.popToRootViewController(animated: true)
    }

    @IBAction func okBtnClicked(_ sender: Any) {
        guard let players = Int(playersTextBox.text!) else {
            makeAlert(title: "Enter a Number", message: "Please enter a number and then press Ok")
            return
        }
        if players < 2 {
            makeAlert(title: "Incorrect Number", message: "Please input more than \(playersTextBox.text!)")
        } else if players > 50 {
            makeAlert(title: "Incorrect Number", message: "Please input less than \(playersTextBox.text!)")
        } else {
            gameInfo.player = players
            self.performSegue(withIdentifier: "ServerView", sender: self)
        }
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let playerController = segue.destination as! ServerSelectViewController
        playerController.gameInfo = gameInfo
    }


    func makeAlert (title: String, message: String) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)

        alert.addAction(UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: {(action) in
            alert.dismiss(animated: true, completion: nil)}))
        self.present(alert, animated: true, completion: nil)
    }

This is my Model.

class GameInfo: Codable {
    var player: Int
    var numberPicked: Int
    var datePlayed: Date
    var winner: String
    var turn: Int

    init(player: Int, numberPicked: Int, datePlayed: Date, winner: String, turn: Int) {
        self.player = player
        self.numberPicked = numberPicked
        self.datePlayed = datePlayed
        self.winner = winner
        self.turn = turn
    }


    static func loadGameInfo() -> [GameInfo] {
        return []
    }


    static let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

    static let archiveURL = documentsDirectory.appendingPathComponent("gameInformation").appendingPathExtension("plist")

    static func saveToFile(gameInformation: [GameInfo]) {
        let propertyListEncoder = PropertyListEncoder()
        let gameInfo = try? propertyListEncoder.encode(gameInformation)

        try? gameInfo?.write(to: archiveURL, options: .noFileProtection)
    }

    static func loadFromFile() -> [GameInfo]? {
        guard let gameInfo = try? Data(contentsOf: archiveURL) else { return nil }

        let propertyListDecoder = PropertyListDecoder()

        return try? propertyListDecoder.decode(Array<GameInfo>.self, from: gameInfo)
    }
}
pkamb
  • 33,281
  • 23
  • 160
  • 191
Mark
  • 47
  • 6
  • Problem is `var gameInfo:GameInfo!`. You never give it a value. – matt Dec 08 '19 at 01:01
  • 3
    Possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – pkamb Dec 08 '19 at 01:50

1 Answers1

2

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

so check the implicitly unwrapped optionals in your code.

Your options seem to be:

@IBOutlet weak var playerButton: UIButton!
@IBOutlet weak var playersTextBox: UITextField!
var gameInfo:GameInfo!

Which one is never assigned a value?

pkamb
  • 33,281
  • 23
  • 160
  • 191
  • Checking now I will return back soon :). – Mark Dec 08 '19 at 01:10
  • After doing some debugging it seems the problem right now is var gameInfo:GameInfo! as you specified earlier in your comment. I input 2 into my text field and the value 2 is being held in Players. But once it gets passed to gameInfo!.player it gives me that error. – Mark Dec 08 '19 at 01:37
  • @Mark your `gameInfo` variable should not be an Implicitly Unwrapped Optional (`!`). Just make it a regular Optional: `var gameInfo: GameInfo?`. That will surface the errors in your code without crashing. – pkamb Dec 08 '19 at 01:43
  • :) It is fixed I overlooked a few things and with your help all is well. Thanks! – Mark Dec 08 '19 at 01:49