How to easily find unused Swift code in Xcode

Gabriel Lewis
2 min readAug 11, 2018

--

Stay sane and remove unused code in Xcode easily with this ruby script. Add the script in a ruby file in your projects main folder called unused.rb. You can either run the code in the terminal with:

$ ruby unused.rb

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

Terminal output

If you’d like to have it be easily displayed in Xcode, navigate to your projects run scripts under Build Phases. Add the following shell script to run unused script automatically:

file="unused.rb"if [ -f "$file" ]thenecho "$file found."ruby unused.rb xcodeelseecho "unused.rb doesn't exist"fi

Afterwards run your project and the unused code warnings should be visible in the build time warnings pane.

Xcode output

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 like collectionView’s numberOfSectionsInCollectionView.

False positive

If you don’t want to bother your coworkers with this script warning output, add the unused.rb file to your projects .gitignore (the run script above checks for its existence before running it).

If this script doesn’t work for you, check out the Periphery App by Ian Leitch.

Credit to Paul Taykalo for his really useful script.

Follow me for more tips on Xcode, Swift and iOS Development

--

--