AppCode 2021.1 Help

Extract variable

If you come across an expression that is hard to understand, or it is duplicated in several places throughout you code, you can place the result of such expression or its part into a separate variable using the Extract Variable refactoring ⌃⌥V.

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 ⌃⌥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 .

Code examples

BeforeAfter
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) } }
BeforeAfter
- (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: 23 April 2021