Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/103.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 类没有初始值设定项_Ios_Cocoa Touch_Swift - Fatal编程技术网

Ios 类没有初始值设定项

Ios 类没有初始值设定项,ios,cocoa-touch,swift,Ios,Cocoa Touch,Swift,我得到了这个错误,但我不知道如何修复它 class GameView2: UIViewController { @IBOutlet weak var resetButton: UIButton! @IBOutlet weak var resultLabel: UILabel! @IBOutlet weak var player1ScoreLabel: UILabel! @IBOutlet weak var player2ScoreLabel: UILabel!

我得到了这个错误,但我不知道如何修复它

class GameView2: UIViewController {

    @IBOutlet weak var resetButton: UIButton!
    @IBOutlet weak var resultLabel: UILabel!
    @IBOutlet weak var player1ScoreLabel: UILabel!
    @IBOutlet weak var player2ScoreLabel: UILabel!

    var selectedPlayer: Int!
    var currentPlayerMove: Int
    var previousPlayerMove: Int!
    var player1Score: Int
    var player2Score: Int

在swift中,必须初始化所有非可选存储属性,可以是内联的,也可以是初始值设定项

在您的类中有6个可选属性(全部定义为隐式展开,以
结尾的属性)和3个非可选属性(
currentPlayerMove
player1Score
player2Score
)。您应该以内联方式初始化它们:

var currentPlayerMove: Int = 0
var player1Score: Int = 0
var player2Score: Int = 0
或在初始值设定项中,或使其可选,或使其隐式展开选项:

var currentPlayerMove: Int!
var player1Score: Int!
var player2Score: Int!
并在使用它们之前初始化-一个好地方是
viewDidLoad

func viewDidLoad() {
    super.viewDidLoad()

    currentPlayerMove = 0
    player1Score = 0
    player2Score = 0        

    ...
}
一些准则:

  • 如果属性可以为nil,则使用普通可选项
  • 如果属性不应为nil,但不能在内联或初始值设定项中初始化,则使用隐式展开可选-警告:当属性为nil时访问隐式展开会导致运行时异常,请务必在使用前正确初始化
  • 如果属性不应为nil,并且您可以内联或在初始值设定项中初始化,则使用非可选选项-这应始终是首选解决方案,而不是隐式展开(如果可能)
您需要一个init()方法来填写currentPlayerMove、player1Score和player2Score,因为它们既不是可选的,也不是隐式展开的选项