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 a variable
In the editor, select an expression or its part you want to extract or just place the caret within this expression.
Press ⌃⌥V or select
from the main menu.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.
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.
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 (withlet
). 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
):
Press ⏎.
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];
}
}
|