Swift: Find Unused Code
Want to find all the unused Swift code in your Xcode project?
We’re going to use Periphery. It’s a free tool, and extremely accurate.
First we need to install Homebrew — if you already have Homebrew installed, you can skip this step.
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Next, we need to tell Homebrew where to find Periphery releases.
brew tap peripheryapp/periphery
And finally, install Periphery itself.
brew cask install periphery
Scan your project
Now that Periphery is installed, we’re ready to let it scan our Xcode project. Change to your project directory and run:
This will begin a guided setup. The first step is to choose the build targets you want to analyze. It’s important you choose the right targets. Let’s say
ClassA is a member of the target
AcmeKit, and it’s only used in once place: by
ClassB in target
AcmeApp. If you choose to only analyze
AcmeKit, Periphery will not be able to identify that it’s used by
AcmeApp. So in this example it’s important we analyze both
Next, we need to tell Periphery which schemes are needed to build our chosen targets.
Now we need to decide if classes, functions, enums, etc... that are marked
public should be assumed to be in use, or not. If your project contains an application that consumes all
public interfaces choose
No, or if your project is just a framework choose
Finally we need to tell Periphery to assume that anything annotated with
@objc is in use, so for now just choose
Yes. You can always come back later and experiment with different options when you’re feeling a little more adventurous.
Hit enter, Periphery will begin scanning your project and finish with a list of unused declarations.
Congratulations! You can now start removing the unused code from your project. But first, let’s make this a much nicer experience by integrating Periphery into Xcode.
The first step is to create a new
Aggregate target, listed under
Cross-platform in the new target popover. Name it
Periphery, click the
Finish button and select the
Build Phases tab.
Next we need to create a new
Run Script Phase. Once created, simply copy and paste the command output previously by Periphery’s guided setup.
If needed, you can find a more detailed guide here: Periphery Xcode Integration.
Now select the new Periphery scheme and click run. Once periphery has analyzed your project, you will see unused code warnings just like regular build warnings.
Now you’ve got Periphery up and running you should familiarize yourself with all the available features.
periphery help scan will give you a list of available options, and the documentation will help you get the most out of Periphery.
Happy unused code hunting!