【发布时间】:2017-09-03 00:31:52
【问题描述】:
我在玩 RoShambo 的应用程序上取得了一些进展,但在一件特别的事情上遇到了困难。在一个 ViewController 中,我建立了该类的两个属性。我希望它们是整数,因为稍后我会在课程中使用带有整数的 switch 语句。但是,当我使用整数表示时出现错误:
"Class 'ResultsViewController' has no initializers"
"stored property 'your play' without initial value prevents synthesized initializers"
现在,如果我将存储的属性设为可选项,这些错误就会消失,但是我的 switch 语句会出现错误,因为它使用整数,而不是可选项。
所以我有两个问题:1)在下面的 switch 语句中,我将如何使用“Int”类型的值?在 switch 语句中?
2) 如果我的可选值为 nil,我怎么能结束程序而不执行 switch 语句,因为进行比较没有意义?
import Foundation
import UIKit
class ResultsViewController: UIViewController {
// MARK: Properties
var opponentPlay: Int?
var yourPlay: Int?
//Mark: Outlets
@IBOutlet weak var MatchResult: UILabel!
@IBOutlet weak var PlayAgainButton: UIButton!
//Mark: Life Cycle
override func viewWillAppear(_ animated: Bool){
//unwrap optional properties
if let opponentPlay = opponentPlay {
print("good play")
} else {
print("opponentPlay is nil")
}
if let yourPlay = yourPlay {
print("good play")
} else {
print("opponentPlay is nil")
}
switch (opponentPlay, yourPlay) {
case (1, 1), (1, 1), (2, 2), (2, 2), (3, 3), (3, 3):
self.MatchResult.text = "You Tie!"
case (1, 2):
self.MatchResult.text = "You Win!"
case (2, 1):
self.MatchResult.text = "You Lose!"
case (1, 3):
self.MatchResult.text = "You Lose!"
case (3, 1):
self.MatchResult.text = "You Win!"
case (2, 3):
self.MatchResult.text = "You Win!"
case (3, 2):
self.MatchResult.text = "You Lose!"
default:
break
}
【问题讨论】:
-
请查看this thread。
标签: ios swift if-statement switch-statement optional