2017-09-03 91 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 
    } 
    } 
}