AppCode 2023.1 Help

Extract variable

If you come across an expression that is hard to understand or it is duplicated in several places throughout your code, the Extract Variable refactoring Ctrl+Alt+V can help you deal with those problems placing the result of such expression or its part into a separate variable that is less complex and easier to understand. Plus, it reduces the code duplication.

Extract variable

Extract a variable

  1. In the editor, select an expression or its part you want to extract or just place the caret within this expression.

  2. Press Ctrl+Alt+V or select Refactor | Extract/Introduce | Extract Variable from the main menu.

  3. If you've placed the caret within the expression, AppCode will offer you a list of potential code selections. Choose the desired selection from the list.

  4. If the expression you want to extract is used multiple times, you can select whether you want to replace all occurrences or just the current one.

  5. If necessary, change the default variable name and use additional options:

    • For Swift: check Declare with 'var' if you want to declare a variable (with var). Deselect this checkbox to declare a constant (with let). Uncheck Specify type explicitly if you don't want to add a data type to the variable declaration.

    • For Objective-C: check Declare const to declare a new reference as a constant (with const):

  6. Press Enter.

Code examples

Before

After

private func performLogin() { // email: self.textFieldEmail.text ?? will be extracted // to the email variable let isEmailValid = self.emailValidator.isEmailValid(email: self.textFieldEmail.text ?? "") if (isEmailValid == true) { self.loginModel.login(email: self.textFieldEmail.text ?? "") } }
private func performLogin() { // Extracted variable let email = self.textFieldEmail.text ?? "" let isEmailValid = self.emailValidator.isEmailValid(email: email) if (isEmailValid == true) { self.loginModel.login(email: email) } }

Before

After

- (void)performLogin { // self.textFieldEmail.text will be extracted // to the email variable BOOL isEmailValid = [self.emailValidator isEmailValid:self.textFieldEmail.text]; if (isEmailValid == NO) { [self.loginModel loginWithEmail:self.textFieldEmail.text]; } }
- (void)performLogin { // Extracted variable NSString *email = self.textFieldEmail.text; BOOL isEmailValid = [self.emailValidator isEmailValid:email]; if (isEmailValid == NO) { [self.loginModel loginWithEmail:email]; } }
    Last modified: 21 July 2022