我在玩RoShambo的应用程序方面取得了一些进展,但我对一件特别的事情感到难过。在一个ViewController中,我已经建立了该类的两个属性。我希望它们是整数,因为我稍后在类中使用带有整数的switch语句。但是,当我使用整数说:
时,我收到错误"Class 'ResultsViewController' has no initializers"
"stored property 'your play' without initial value prevents synthesized initializers"
现在,如果我创建了我的存储属性选项,那些错误就会消失,但是我的switch语句会出现错误,因为它使用的是整数,而不是选项。
所以我有两个问题:1)在下面的switch语句中,我将如何使用" Int?"类型的值?在switch语句中?
2)如果我的可选值为零,我怎么能结束程序而不执行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
}
答案 0 :(得分:1)
您可以使用?
打开包装。您还可以添加where
条款,如果您不想列举每个排列,无论您是赢还是丢失:
switch (opponentPlay, yourPlay) {
case (nil, nil):
print("both nil")
case (nil, _):
print("opponent score nil")
case (_, nil):
print("yours is nil")
case (let opponent?, let yours?) where opponent == yours:
matchResult.text = "tie"
case (let opponent?, let yours?) where opponent > yours:
matchResult.text = "you win"
case (let opponent?, let yours?) where opponent < yours:
matchResult.text = "you lose"
default:
fatalError("you should never get here")
}
答案 1 :(得分:1)
我执行的代码与您的代码类似,但不会产生错误。我真的不知道switch是否接受选项,但我认为在这种情况下它也没有必要。我希望它对你有用。
var opponentPlay: Int?
var yourPlay: Int?
var matchResult = ""
func play (){
if let opponentPlay = opponentPlay , let yourplay = yourPlay {
switch (opponentPlay,yourplay) {
case (1,1):
matchResult = "You tie"
default:
break
}
}
}