2017-09-03 8 views
1

私はRoShamboを再生するために私のアプリでいくつかの進歩を遂げましたが、1つの特定のことに困惑しています。 1つのViewControllerでは、クラスの2つのプロパティを設定しました。後で整数でクラス内でswitch文を使うので、それらを整数にしたい。私が言って整数を使用する場合しかし、私はエラーを取得する:私は私の保存されたプロパティのoptionalsを作る場合Switch文でオプションのIntsを使用する方法

"Class 'ResultsViewController' has no initializers" 
"stored property 'your play' without initial value prevents synthesized initializers" 

は今、これらのエラーが離れて行くが、それは、整数ではなく、optionalsを使用しているので、私は私のswitch文でエラーが発生します。

私は以下の2つの質問があります: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 
    } 
+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 
    } 
    } 
} 
関連する問題