0

My ViewController

/ MARK: Properties
@IBOutlet weak var textInput: UITextField!

@IBOutlet weak var labelTop: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()        
    textInput.delegate = self
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
}

func textFieldDidEndEditing(textField: UITextField) {
    if (textInput != nil){
        labelTop.text = "Searching for \(textField.text)"
        textInput.enabled = false
    }                           
}

When I press return on the textfield the code

labelTop.text = "Searching for \(textField.text)"

is called. However the text of labelTop looks like:

Searching for Optional("the text")

I looked at optionals (most times they use ? instead of ! right?) but do not understand how I should get the value without the surrounding 'Optional("")'

Sven van den Boogaart
  • 11,833
  • 21
  • 86
  • 169

1 Answers1

1

You need to unwrap the optional value.

if let text = textInput?.text {
    labelTop.text = text
    textInput.enabled = false
}    
Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
  • But I thought you didn't need to unwrap implicitly unwrapped optionals https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID334 – Sven van den Boogaart Jan 15 '16 at 22:48
  • 1
    Correct, but the `text` property of `UITextField` is `Optional` as well and it's **not** `Implicity Unwrapped`. So it does need to be unwrapped. – Luca Angeletti Jan 15 '16 at 22:51
  • Ah thanks I assumed there was some kind of inheritance on unwrapping – Sven van den Boogaart Jan 15 '16 at 22:52