【问题标题】:random number statement is not working with my toInt text field input随机数语句不适用于我的 toInt 文本字段输入
【发布时间】:2015-06-30 05:50:37
【问题描述】:

以下错误:无法使用类型为 '(@lvalue Int?, @lvalue UInt32) 的参数列表调用 '=='

@IBOutlet weak var textBox: UITextField!

@IBOutlet weak var result: UILabel!

@IBAction func submit(sender: AnyObject) {
    var randomNumber = arc4random_uniform(4)+1//look at the first if declaration. This is were my question is
    var guess = textBox.text.toInt()
    if guess == randomNumber {             //error: Cannot invoke '==' with an argument list of type '(@lvalue Int?, @lvalue UInt32)
        guess.text = "Well done, correct!"
    }
    else if guess < 0 {
        guess.text = "WHAT!?!? that wasn't even an option"
    }
    else if guess > 5 {
        guess.text = "WHAT!?!? that wasn't even an option"
    }
    else {
        guess.text = "WRONG the correct answer was \(randomNumber)"
    }

请告诉我为什么我在使用 == 和 arcforrandom 时会出错,以及如何解决这个问题并让它像我想要的那样运行。非常感谢所有答案

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    Uint 转换为Int

    var randomNumber = Int( arc4random_uniform(4)+1 )
    

    和..

    为什么guess.text 你的意思是result.text

    【讨论】:

      【解决方案2】:

      您的 randomNumber 是 UInt32 类型。您必须将其转换为 Int。 你可以在Apple Documentation阅读它

      var randomNumber = Int(arc4random_uniform(4)+1)
      

      【讨论】:

        【解决方案3】:

        UInt 表示 unsigned int 此处只允许使用正数。

        Int 允许正面和负面

        但两者的范围相同 (2^31)

        所以将您的UInt 转换为Int

         if guess == Int(randonNumber) { 
        

        【讨论】:

          猜你喜欢
          • 2015-12-02
          • 2013-03-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-08-09
          • 1970-01-01
          • 2016-12-07
          • 1970-01-01
          相关资源
          最近更新 更多