How to Find Unused Swift Code with Periphery Static Analyzer

How to check and find unused Swift code in Xcode projects

Recently I faced an issue with compile -O for product build. I assumed that It caused by dead function issue. I reported it

Apple Swift Git Repo

This post I’ll introduce static analyzer tool for checking the unused swift codes

Install Periphery

Link You can install periphery tool using homebrew

Here is homebrew install command.

brew install peripheryapp/periphery/periphery

And then setup peripheryapp on your project

periphery scan --setup

34ff6 72338 screenshot2023 06 03at11.33.08pm

Select your App’s target name. Don’t forget to save configuration to .periphery.yml

Check unused codes

You can see the results.

50103 2554a screenshot2023 06 03at11.38.15pm

Make a script file to save result as text file

I recommend make a bash script file to save results as text file to keep track progress of reducing unused codes. Here is the bash script. (I changed ruby code (https://www.youtube.com/watch?v=2OQiCj-BG2o) to bash script)

#!/bin/bash
echo "🔍 start dead code analysis"
result="$(periphery scan --config .periphery.yml)"
current_dir=$(pwd)
result_stripped_of_absolute_path_prefix=$(echo "$result" | sed "s|$current_dir/||g")
filtered_out_result=$(echo "$result_stripped_of_absolute_path_prefix" | awk '/:[0-9]+:[0-9]+:/{ print }')
sorted_result=$(echo "$filtered_out_result" | sort)
result_with_removed_code_line_number=$(echo "$sorted_result" | sed "s|:[0-9]+:[0-9]+:|:|")
output=$(echo "$result_with_removed_code_line_number" | tr '\n' '\n' | sort)
echo "$output" > unused-codes.txt 2>&1
echo "🙌 done with dead code analysis"

I saved bash script file as check-unused-codes.sh

You can run bash script file by running sh check-unused.codes.sh in terminal (You can see the results of the unused codes)

25550 79731 screenshot2023 06 04at1.24.26am

fd2e5 cc6e4 screenshot2023 06 04at1.24.38am

Results will be saved into the unused-codes.txt

Reference

Inside iOS Dev

https://www.parasoft.com/blog/false-positives-in-static-code-analysis/