R. R
R. R

Reputation: 55

Force Unwrap Optionals from UITextfield

I'm trying to get a value from a UITextfield and it's being returned as optional. I've tried suggested methods of force unwrapping and I'm still receiving Optional("WhateverUserInputHere") instead of 'WhateverUserInputHere'. I've also been looking for a way to make sure the textfield is not empty before retrieving the value, to keep from crashing when force unwrapping. As of now, the value is retrieved after the user hits a button to move to the next screen, and this button is only enabled once the user begins to edit the textfield. If they decide to delete everything within the textfield, however, they can still move forward. Any way to prevent this/make sure button is only enabled once user has finished typing and textfield is not empty?

// Variable used to store value from textfield    
var nametemp:String?
    var name:String = ""

    @IBOutlet weak var NameInput: UITextField!
    @IBOutlet weak var NextButton: UIButton!
    @IBOutlet weak var TestLabel: UILabel!


// Enables button when textfield has been edited
    @IBAction func NameInputEditingDidChange(_ sender: Any) {
        NextButton.isEnabled = true
    }

   // When button is used, value of textfield is retrieved
    @IBAction func NextButtonVariableTest(_ sender: Any) {
        nametemp = String(describing: NameInput.text)
        name = nametemp!
// Label returns optional value

TestLabel.text = "Hello" + name

    }

}

Upvotes: 1

Views: 641

Answers (1)

Sulthan
Sulthan

Reputation: 130162

Simply use

self.name = NameInput.text!

or

self.name = NameInput.text ?? ""

Once you use String(describing:) the Optional(...) text will be part of your string rather than an optional string and you won't be able to remove it.

Upvotes: 2

Related Questions