Darth Washington Darth Washington - 1 year ago 90
Swift Question

Assigning text field value to variable in Swift

I am trying to learn Swift and it is turning out to be more different from other languages than I expected...

I just want to store the value of a user's input as an integer in a variable.

My attempts result in the following error:
"fatal error: unexpectedly found nil while unwrapping an Optional value"

I have tried this multiple ways and can't seem to come up with a solution, I know there must a simple way to do this.

var intNumber: Int = 0
@IBOutlet weak var txt_Number: UITextField!

for view in self.view.subviews as [UIView]{
if let txt = view as? UITextField
if let txtData = txt.text where txtData.isEmpty
// Error Message
intNumber = Int(txt_Number.text)

I know the above code isn't correct, but I think that's the closest to correct I have come. I seem to be missing something as far as unwrapping goes. I understand the principal of unwrapping, but nothing I have tried will compile, or if it does compile then it fails with the error above when the code is initiated (code is initiated when a button is pressed).

Thank you in advanced for any help!

Rob Rob
Answer Source

A couple of thoughts:

  1. Make sure your outlet is hooked up to txt_Number. All of that code checking to make sure it's not nil is not necessary if (a) it's an outlet you hooked up in IB; and (b) you're not doing the above code before the view is completely loaded (i.e. viewDidLoad was called).

    If the outlet is not hooked up, you'll see an empty dot on the left margin:

    enter image description here

    If it is hooked up correctly, you'll see a filled in dot on the left margin:

    enter image description here

  2. If everything is hooked up correctly, you can just do:

    guard let txtData = txt_Number.text, let value = Int(txtData) else {
        // report error and then `return`
    intNumber = value
  3. If you want to get fancy, you might want to ensure the user only enters numeric values by

    • In viewDidLoad, specify that the keyboard is for decimal numbers only.

      txt_Number.keyboardType = .NumberPad

      Or you can specify this in IB, too.

    • Specify a delegate for the text field and only allow them to enter numeric values. (This might seem redundant based upon the prior point, but it's not, because you have to also anticipate them pasting in a string to the text field.)

    See http://stackoverflow.com/a/26940387/1271826.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download