2017-09-03 33 views
1

我的應用程序在使用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 
    } 
+0

請檢查[此主題](https://stackoverflow.com/q/37452118/6541007)。 – OOPer

回答

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

我已經執行類似你這樣的代碼,它不會產生錯誤。我真的不知道開關是否接受可選項,但我認爲在這種情況下它也不是必需的。我希望它對你有用。

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 
    } 
    } 
}