Guilherme Marques
Guilherme Marques

Reputation: 75

When trying to convert a UITextField text to Int Xcode 7 gives me an error

I'm new to programming and after doing some tutorials online I decided to make my own app with Xcode 7 to be able to run my app on my iPhone. But when I try to get input data from a text field and put it into a var it gives me an error. I have tried to use the following:

var initialChips = 0
var initialBlind = 0

@IBOutlet weak var txtBlind: UITextField!
@IBOutlet weak var txtChips: UITextField!
@IBOutlet weak var doneBtn: UIBarButtonItem!

@IBAction func doneBtn(sender: AnyObject) {

    let initialChips:Int? = Int(txtChips.text)
    let initialBlind:Int? = Int(txtBlind.text)
}

Xcode will ask to put a "!" after ".text" but after doing that it gives me a warning: "Initialization of immutable value 'initialChips' (or 'initialBlind' was never used: consider replacing with assignment to '_'or removing it".

What can I do to set a value to my var?

Upvotes: 2

Views: 1973

Answers (2)

FabKremer
FabKremer

Reputation: 2169

The thing is that the let initialChips:Int? = Int(txtChips.text) generates a new variable called initialChips (different from the variable from the class). The difference between let and var is that let is inmutable and var is not. You should do:

initialChips = Int(txtChips.text)

To assign the integer from the UITextField to your class variable rather than declaring a new inmutable variable (with the same name) and do nothing with it.

Of course, the same happens with initialBlind

EDIT:

Try the following:

@IBAction func doneBtn(sender: AnyObject) {

    if let initialChips = Int(txtChips.text!) {
        self.initialChips = initialChips
    }else {
        self.initialChips = 0
    }

    if let initialBind = Int(txtBind.text!) {
        self.initialBind = initialBind
    }else {
        self.initialBind = 0
    }
}

Upvotes: 2

Goran Blažič
Goran Blažič

Reputation: 86

You should add the ! after the closing parenthesis, not after .text, like so:

let initialChips:Int? = Int(txtChips.text)!

Upvotes: 0

Related Questions