我的應用程序在使用RoShambo方面取得了一些進展,但我難以忍受某種特定的事情。在一個ViewController中,我已經建立了這個類的兩個屬性。我希望它們是整數,因爲我稍後在整數類中使用switch語句。不過,我得到一個錯誤,當我使用整數說:如何在Switch語句中使用可選Ints
"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
}
請檢查[此主題](https://stackoverflow.com/q/37452118/6541007)。 – OOPer