user4571832
user4571832

Reputation:

Class 'ViewController' has no initializers - Similar questions couldn't resolve issue

I have searched for similar questions, but they could not resolve my issue, so I hope it's ok, that I am asking it again. Here is my code:

import UIKit

class ViewController: UIViewController {

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

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBOutlet weak var revealLabel: UILabel!
@IBOutlet weak var scoreLabel: UILabel!
@IBOutlet weak var textField: UITextField!

var userGuess: Int
var heldUpFingers: Int
var score: Int = 0

@IBAction func startGame(sender: UIButton) {
    userGuess = Int(textField.text!)!
    if textField.text == nil {
        revealLabel.text = "Please enter a number from 1 to 5"
    } else if userGuess > 5 {
        revealLabel.text = "Please enter a number from 1 to 5"
    } else {
        heldUpFingers = Int(arc4random_uniform(5) + 1)
        if heldUpFingers == userGuess {
            revealLabel.text = "You guessed right!"
            score += 1
            scoreLabel.text = String(score)
        } else {
            revealLabel.text = "Wrong, it was \(heldUpFingers)"
        }
    }

}

}

It gives me the error "Class 'ViewController' has no initializers" in the 3rd line. Thanks in advance!

Upvotes: 0

Views: 62

Answers (1)

Joe Benton
Joe Benton

Reputation: 3753

It is because userGuess and heldUpFingers aren't assigned yet. You can either make these optional by adding a ? after the Int or by setting a default value to them. So either:

var userGuess: Int?
var heldUpFingers: Int?

You will then need to unwrap them/check there not nil later in your code like this:

if userGuess != nil {
    //now safely use userGuess!
}

Or

var userGuess: Int = 0
var heldUpFingers: Int = 0

Upvotes: 1

Related Questions