How to find unused Swift code

We create variable and method at beginning of development but sometimes some of them remain unused but we forgot to remove them. Also it’s difficult to identify which variable or method is unused. They are only there for memory consumption.

You can remove unused code easily with this ruby script. Download this file and add in your X-code project. You can also create a new file unused.rb in Xcode and add this script.

Now navigate to you project in terminal and run this command

$ ruby unused.rb

The terminal will spit out a list of unused functions and variables found in your project.

Wow !!! all the unused variables & method will display on terminal but it’s hard to open each file and remove that variable, we need to displayed in Xcode.

Open Xcode project and add a run scripts under Build Phases. Add the following shell script to run unused script automatically:

Now, run your project and the unused code warnings will be visible in the build time warnings pane.

Keep in mind this code will have a lot of false positives (protocols, functions, and system delegates) and false negatives, so be careful when deleting any “unused” delegate methods.

Note: Remove the file unused.rb before making code live.

Thanks 🙏🙏

iOS App developer