Extract closure
The Extract Closure refactoring creates a closure out of the selected chunk of code.
Extract a closure
In the editor, select an expression which you want to extract into a closure.
Press Ctrl+Alt+Shift+T and select Extract Closure. Alternatively, select from the main or context menu.
If there are several expressions available for extracting, select the required one from the list that opens and press Enter.
In the dialog that opens, type the name of the new closure and change the parameter names and types if necessary.
Press Enter.
Code example
Before | After |
---|---|
private func performLogin() {
let email = self.textFieldEmail.text ?? ""
let isEmailValid = self.emailValidator.isEmailValid(email: email)
// To be extracted
textFieldEmail.textColor = isEmailValid ? UIColor.black : UIColor.red
}
|
private func performLogin() {
let email = self.textFieldEmail.text ?? ""
let isEmailValid = self.emailValidator.isEmailValid(email: email)
// Extracted closure
let setFiledStyle = { (isEmailValid: Bool) in
self.textFieldEmail.textColor = isEmailValid ? UIColor.black : UIColor.red
}
setFiledStyle(isEmailValid)
}
|
Last modified: 14 December 2022