Mateo Villagomez Mateo Villagomez - 3 months ago 10
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


Into:

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

Answer

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

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

Then call it like this:

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