Mateo Villagomez Mateo Villagomez - 1 year ago 52
Swift Question

Is there any way to perform delegation through a function?

With purposes avoiding repetition, how can you convert something like this:

self.upperTextField.delegate = self
self.lowerTextField.delegate = self


func setDelegates(textField: UITextField){
textField.delegate = self
print("delegates set")

Answer Source

You could modify your function to accept an array of UITextField objects:

func setDelegates(delegate: UITextFieldDelegate, textFields: [UITextField]) { {
        $0.delegate = delegate
    print("delegates set")

Then call it like this:

setDelegates(self, textFields: [upperTextField, lowerTextField])