我搜索过类似的问题,但他们无法解决我的问题,所以我希望没问题,我再问一遍。这是我的代码:
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)"
}
}
}
}
它在第3行给出了错误“Class'ViewController'没有初始值设定项”。提前谢谢!
答案 0 :(得分:1)
这是因为userGuess
和heldUpFingers
尚未分配。您可以通过在?
之后添加Int
或为其设置默认值来使这些可选。所以:
var userGuess: Int?
var heldUpFingers: Int?
然后你需要打开它们/检查你的代码后面不会这样:
if userGuess != nil {
//now safely use userGuess!
}
或者
var userGuess: Int = 0
var heldUpFingers: Int = 0