我收到此错误,我一生都无法弄清为什么它返回nil值。
致命错误:在隐式展开可选值时意外发现nil
错误发生在:
} else {
gameInfo.player = players
self.performSegue(withIdentifier: "ServerView", sender: self)
}
以下是我从表视图控制器开始的全套代码。
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)
}
这是我的模特。
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)
}
}
答案 0 :(得分:2)
致命错误:意外发现nil ,同时隐式展开一个可选值
因此请检查代码中隐式展开的可选内容。
您的选择似乎是:
hanoi(3,"a","b","c")
哪个从未分配过值?