Swift 1.0将字符串转换为int错误

时间:2015-10-18 00:04:31

标签: string xcode6 int swift2

此代码在swift 1.0中运行良好,除非我尝试使用swift 2.0运行它时它给了我一个错误.....有人可以解释为什么swift给我这个错误并告诉我如何修复它? (我已经对堆栈溢出进行了一些挖掘,试图找到解决方案,但找不到它)

谢谢!继承人代码:

class ViewController: UIViewController {@IBOutlet var guess: UITextField!





@IBOutlet var label: UILabel!


@IBAction func guessButton(sender: AnyObject) {




    var randomnumber = arc4random_uniform(6)


    var guessInt = guess.text!.toInt()


    if guessInt != nil {


        if Int(randomnumber) == guessInt {

            label.text = "correct"


        } else {

            label.text = "nope it wsa \(randomnumber)"

        }





    } else {


        label.text = "enter a number"


    }


    print(guess.text)








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

}

1 个答案:

答案 0 :(得分:0)

我不确定你收到了什么错误信息,但有一点我看错了以下内容:

var guessInt = guess.text!.toInt()

您应该使用Int(value)代替。您还可以在if字符串中初始化guessInt以检查值是否为nil:

if let guessInt = Int(guess.text!) {

    //Do things

} else {

    //Value was nil

}