Search code examples
swiftxcodeuitextfieldsegueibaction

How to return(skip the rest of) a function in swift if conditions are met


I have a segue set up to perform when a button is pressed. I want to end the function and void the segue if the text field in the current view controller is nil. No luck so far. How would I go about doing this? Here is what I have:

@IBAction func myButton(_ sender: Any) {
    if textField.text == nil {

        return

    } else {

    performSegue(withIdentifier: "theSegue", sender: sender)

    }
}

Thanks in advance.


Solution

  • Although the documentation implies it (declared as optional), the text property is actually not nil (This string is @"" by default).

    I recommend to check additionally for empty string.

    @IBAction func myButton(_ sender: Any) {
       guard let text = textField.text, !text.isEmpty else { return }
       performSegue(withIdentifier: "theSegue", sender: sender)
    }