Xcode Refactoring Tool Basics: Save Your Coding Time

Xcode refactoring tool can be a nice time saver. Better yet the refactoring features are extremely simple to learn and adapt to.

Xcode refactoring engine has been around for a while, but I’m sure many of us haven’t still found it or had no time to explore its useful features.

This utility tool can be used to transform code both within a single file and over multiple files. For example, you can easily rename a method that is used in multiple files all at once.

Rename Code Using Xcode Refactoring

Avoid manual repetitive work when renaming variables, methods, etc. using renaming features in the Xcode refactoring tool.

Rename Code Using the “Rename” Feature

This feature finds all the places in which the piece of code is used and renames it according to you:

Edit all references of the ‘number’ variable everywhere where it’s being used.

Rename Code Using “Edit All in Scope”

You can rename a piece of code in a specific file by command+clicking and renaming a piece of code as follows:

Edit all references of the ‘number’ variable in the current file.

Multi-Cursor Edit with Xcode Refactoring

shift + control + left mouse click

You can easily multi-cursor edit code in these 4 ways:

  • shift+control+left mouse click—create a new cursor on each click (this is shown in the above gif)
  • shift+control+arrow up — create a new cursor at a line above
  • shift+control+arrow down — create a new cursor at a line below
  • option+drag — create new cursors on each line over which you drag

Extract Methods Using Xcode Refactoring

You can make your code readable and concise by extracting pieces of code to separate methods. You can save time by doing this with the built-in refactoring tool:

Extract Variables Using Xcode Refactoring

Similar to extracting a block of code to a separate method, you can easily extract an expression to a variable:

Extract All Occurences Using Xcode Refactoring

Very similar to the previous 2 examples, you can also extract all occurrences of an identical expression to a variable:

Finding occurrences of UserDefaults.standard.array(forKey: “Names”)! and creating a variable for it

Add Missing Switch Cases Using Xcode Refactoring

If you are using a default case in a switch statement the compiler does not show any error about the missing cases you haven’t covered.

In this case, you can use the Xcode refactoring tool to expand the switch statement to cover all the cases:

Adding the missing cases, South and West.

Thanks for reading. Happy coding!

Scroll to Top