How to easily find unused Swift code in Xcode

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




iOS Engineer |

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Gabriel Lewis

Gabriel Lewis

iOS Engineer |

More from Medium

Every iOS developer should know these Xcode tricks

Swift programming: Classes

UserDefaults Unit testing in iOS

How to Write Images to Camera Roll in iOS

How to Write Images to Camera Roll in iOS