How to run code after return statement in function in Swift?

Consider the following code:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let validator:NSPredicate = NSPredicate(format:"SELF MATCHES %@","[A-Za-z0-9- ]+")
    if(validator.evaluateWithObject(string) || string == "" /* i.e. backspace */) {
        self.process(textField)
        return true
    }
    else {
        return false
    }
}

I want to run self.process (textField) AFTER the return statement, because before it the text in the text field has not changed yet. This made me wonder why I can't just execute some code after the return statement? Why do functions always stop when the return statement is executed?

I understand that traditionally, what does return mean, but is there an alternative? For example, is there a way to return a value from a function and then still continue?

On the one hand, this seems like a stupid question, but on the other hand, I feel that I cannot be the first to ever want to do this. It would be nice if I could remove something to work in the next cycle of the cycle cycle, so maybe there is something in the GCD that could help me.

+4
source share
4 answers

Since Swift 2.0 has a keyword called "defer". This keyword allows us to specify a block of code that will be executed when the current function completes, for cleanup actions or other needs. This block of code will be deferred until the last statement is executed, regardless of whether it is a return statement or any other.

:

func anyFunction(someParameter: Int) -> Int {

    // Some code

    return SomeValue

    defer {

        // This block will be executed at the end of this function and after all statements.

    }

}

"" , .

+4

, .

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    print("view loaded")
    textField.addTarget(self,
        action: "textFieldDidChange:", forControlEvents: .EditingChanged)
}


func textFieldDidChange(textField: UITextField){
    print("text changed: \(theTextField.text)")
    self.process(textField)
}
+1

return. . ; .

willSet / didSet. , String, . , . willSet, process textField .

0

Early injections must be in available code expressions, otherwise they will not be executed at the end of the block. Basically, his main idea is to postpone.

0
source

All Articles