How to easily find unused Swift code in Xcode

Gabriel Lewis
Aug 11, 2018 · 2 min read

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


Gabriel Lewis

Written by

iOS @Imgur | http://gabriellewis.me

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade