gpt4 book ai didi

ios - 如何在 Switch 语句中使用可选整数

转载 作者:搜寻专家 更新时间:2023-11-01 07:09:02 24 4
gpt4 key购买 nike

我在玩 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
}

最佳答案

你可以用 ? 解包。如果你不想枚举每个排列,你也可以添加 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")
}

关于ios - 如何在 Switch 语句中使用可选整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46019326/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com