How to convert a UITextField to an integer in Swift 2.0?

I start quickly and do some tests. Honestly, I barely know what I'm doing, so please try to explain clearly. I was creating an application for a random number generator and wanted to add it to uitextfieldso that the user can enter his guess about the next randomly generated number. I keep getting an error when I try to use the if statement to compare a randomly generated number with the entered number. In the text box.

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {
    @IBOutlet weak var input: UITextField! 
    @IBOutlet weak var infoLabel: UILabel! // Displayed Before The User Clicks Button For The First Time.
    @IBOutlet weak var numberLabel: UILabel!
    @IBAction func go(sender: AnyObject) {
        // Remove The Text Under The Button 
        infoLabel.text = " "

        // Generate Random Number 
        let randomNumber = Int(arc4random_uniform(11))

        // Change The "Number Label's" Text In Order To Show The Randomly Generated Number To The User        
        numberLabel.text = "\(randomNumber)"

        // Check To See If The User Guessed The Correct Number, And If They Did, Tell Them They Were Right
        if input == randomNumber {
            infoLabel.text = "Your Guess,\(randomNumber) Was Correct!"
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}
+4
source share
4 answers

To convert an input string to an integer using Swift 2:

let guess:Int? = Int(input.text)

if guess == randomNumber { 
  // your code here
}
+9
source

To access this int value:

Int(input.text)

UITextField, Int. , , , Int, , Int, , int, .

+3

You can convert the string to int using this:

input.text.toInt (!)

+2
source

in Swift 3, you should compare the equivalent type of number: for example, convert a string to int.

let guess = Int(input.text!)! 
if guess == randomNumber {your code}
-1
source

All Articles