I'm trying to create a coin flip simulation that will log the results of every coin flip in a NSTableView. However, when I go to insert a new row containing the result of the coin flip, I get a Fatal error: Array index out of range despite the index it's trying to insert to being 0. Here is part of my view controller class:
class CoinController: NSViewController {
@IBOutlet weak var shownImage: NSImageView!
@IBOutlet weak var shownText: NSTextField!
@IBOutlet weak var coinSelected: NSPopUpButton!
@IBOutlet weak var tableView: NSTableView!
@objc dynamic var values: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func flipCoin(_ sender: Any) {
let transition = CATransition()
transition.type = CATransitionType.moveIn
let rand = Bool.random()
let currentCoin = coinSelected.titleOfSelectedItem ?? ""
if rand == true {
self.shownImage.image = NSImage(named:currentCoin+"Heads")
values.append("Heads")
} else {
self.shownImage.image = NSImage(named:currentCoin+"Tails")
values.append("Tails")
}
self.shownImage.layer?.add(transition, forKey: "transition")
let last = values.count-1
tableView.insertRows(at: [last], withAnimation: .slideDown)
tableView.reloadData(forRowIndexes: [last], columnIndexes: IndexSet(integersIn: 0..<1))
tableView.scrollRowToVisible(last)
tableView.selectRowIndexes([last], byExtendingSelection: false)
}
And here are my bindings:


