2

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?

  • That warning is not that important, actually. It just warns you that you have never used what you assigned. It must gone when you use initialBlind / Chips in your func. – Kutay Demireren Jul 19 '15 at 23:10

2 Answers2

2

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
    }
}
FabKremer
  • 2,149
  • 2
  • 17
  • 29
  • Thanks for the answer but when I do that it gives me an error and makes me use initialChips = Int(txtChips.text!)! to be able to run the code and when I try to print() it doesn't print. – Guilherme Marques Jul 19 '15 at 23:36
0

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

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