如果陈述错误"预期欺骗"

时间:2014-09-20 23:29:54

标签: ios swift

我想做一个简单的"猜猜多少手指"应用程序。就像你童年时玩过的游戏一样?是的我的一个if语句中有一个奇怪的错误,它说"预期的减速"我只想要文本框/字段中的值等于触发函数的随机数。

这是我的代码。

import UIKit

class ViewController: UIViewController {
//Outlets
    //text box for guessing
    @IBOutlet weak var guessField: UITextField!

    //Correct or Incorrect Display
    @IBOutlet weak var yn: UILabel!

    //Label that shows how many guesses you have left
    @IBOutlet weak var guessesLabel: UILabel!


//Needed Variables
    var randomNumber = arc4random() % 6
    var guesses = 3
//Start Code

    if (guessField == randomNumber){
    //This is where the error appears^^        
    var yn = "Correct!"

    }else{

    guesses - 1
    var yn = "Try again!"
    var guessesLabel = "Remaining Guesses: " + guesses

    }
//Endgame function
    if (guesses > 1){
    var yn = "I was holding up \(randomNumber) fingers!"


    //Endgame function if 1 finger
    if (randomNumber == 1){

        var yn = "I was holding up 1 finger!"


        }

    }


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

3 个答案:

答案 0 :(得分:1)

问题是行if (guessField == randomNumber)以及之后的所有内容都不在任何函数内。您不能在类声明的顶级具有可执行代码。这就是编译器此时告诉您需要声明(例如函数声明)的原因。

答案 1 :(得分:0)

1.guessField是一个包含字符串的文本字段。(甚至对于字符串,它是guessfield.text)

2.您要将整数与字符串进行比较。

所以修复

NSString *strVar=[NSString stringWithFormat:@"%d",var];
if[(guessField.text isEqualToString strVar]){
   // Your code----
}

答案 2 :(得分:0)

你想:

//Needed Variables
    var randomNumber = arc4random() % 6
    var guesses = 3
//Start Code

    if (guessField == randomNumber){
    //This is where the error appears^^        
    var yn = "Correct!"

    }else{

    guesses - 1
    var yn = "Try again!"
    var guessesLabel = "Remaining Guesses: " + guesses

    }
//Endgame function
    if (guesses > 1){
    var yn = "I was holding up \(randomNumber) fingers!"


    //Endgame function if 1 finger
    if (randomNumber == 1){

        var yn = "I was holding up 1 finger!"


        }

    }

成为:

func customFunction() -> //type {

//Needed Variables
    var randomNumber = arc4random() % 6
    var guesses = 3
//Start Code

    if (guessField == randomNumber){
    //This is where the error appears^^        
    var yn = "Correct!"

    }else{

    guesses - 1
    var yn = "Try again!"
    var guessesLabel = "Remaining Guesses: " + guesses

    }
//Endgame function
    if (guesses > 1){
    var yn = "I was holding up \(randomNumber) fingers!"


    //Endgame function if 1 finger
    if (randomNumber == 1){

        var yn = "I was holding up 1 finger!"


        }

    }
}