artie711 artie711 - 6 months ago 124
Swift Question

Swift: label text --> "fatal error: unexpectedly found nil while unwrapping an Optional value"

like it says in the title, i am trying to change label text upon click of a button. Error appears at line

self.playerChoice.text = "You: Rock"


import UIKit

class ViewController: UIViewController {

var player : Int = Int()

@IBOutlet weak var readyLabel: UILabel!

@IBAction func noButton(sender: AnyObject) {
exit(0)
}

// ---------------------------------------------------------

@IBOutlet var computerChoice: UILabel!

@IBOutlet var playerChoice: UILabel!

@IBOutlet var score: UILabel!


// Variables -------------------------------------------------

let Rock : String = "Rock"
let Paper : String = "Paper"
let Scissors : String = "Scissors"

//------------------------------------------------------------



override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

}


// ----------------------------------------------------------------

@IBAction func rockButton(rockbut: UIButton) {

player = 0
var ai = arc4random_uniform(3)
self.playerChoice.text = "You: Rock"

}

@IBAction func paperButton(paperbut: UIButton) {

player = 1
var ai = arc4random_uniform(3)
self.playerChoice.text = "You: Paper"

}

@IBAction func scissorsButton(scissorsbut: UIButton) {

player = 2
var ai = arc4random_uniform(3)
self.playerChoice.text = "You: Scissors"

}
}

Answer

I have tried this code and it working fine for me:

class ViewController: UIViewController {

var player : Int = Int()      //Declare this globally

@IBOutlet weak var readyLabel: UILabel!

@IBAction func noButton(sender: AnyObject) {
    exit(0)
}

// ---------------------------------------------------------

@IBOutlet var computerChoice: UILabel!

@IBOutlet var playerChoice: UILabel!

@IBOutlet var score: UILabel!


// Variables -------------------------------------------------

let Rock : String = "Rock"
let Paper : String = "Paper"
let Scissors : String = "Scissors"

//------------------------------------------------------------

@IBAction func rockButton(rockbut: UIButton) {
     player = 0
    var ai = arc4random_uniform(3)
    self.playerChoice.text = "You: Rock"
}



@IBAction func paperButton(sender: UIButton) {
     player = 1
    var ai = arc4random_uniform(3)
    self.playerChoice.text = "You: Paper"
}

@IBAction func scissorsButton(sender: UIButton) {
     player  = 2
    var ai = arc4random_uniform(3)
    self.playerChoice.text = "You: Scissors"
}



override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    var p : String = "Undecided"

    if (player == 0) {
        var p: String = "Rock"
    } else if (player == 1) {
        var p: String = "Paper"
    } else if (player == 2) {
        var p: String = "Scissors"
    }


    }

}