Swift Code Styles (SwiftLint)

Çağatay Emekci
Mobile Development
Published in
2 min readFeb 4, 2019

Code Styles are the rules or guidelines used when writing the source code for an application. Implementing a specific programming style helps programmers to read and understand the source code. The project I have been working on has been developing for many years. I just wanted the rules to work on the changes made in the files. I researched tools for iOS Code Style. Finally, I decided to use SwiftLint.

Definition of SwiftLint in GitHub, a tool to enforce Swift style and conventions, loosely based on GitHub’s Swift Style Guide. Let’s include in our project. We use to CocoaPods to manage third-party library dependencies. Simply add the following line to your Podfile in your project:

pod 'SwiftLint'

Open the terminal, go to the project file path and install pod. After that, you must write a script to use SwiftLint. Open Xcode and add a new “Run Script Phase” with:

"${PODS_ROOT}/SwiftLint/swiftlint"

When you run your application, the code will give errors if the code does not fit the code style. Simply, we’ve added the tool to our project. But we want the rules to work on the changes made in the files. We need to change a script.

Create a script file with the name “swiftlint.sh” in the project file path and add the following code.

# Run SwiftLint
START_DATE=$(date +"%s")
SWIFT_LINT="${PODS_ROOT}/SwiftLint/swiftlint"
# Run SwiftLint for given filename
run_swiftlint() {
local filename="${1}"
if [[ "${filename##*.}" == "swift" ]]; then
${SWIFT_LINT} autocorrect --path "${filename}"
${SWIFT_LINT} lint --path "${filename}"
fi
}
if [[ -e "${SWIFT_LINT}" ]]; then
echo "SwiftLint version: $(${SWIFT_LINT} version)"
# Run for both staged and unstaged files
git diff --diff-filter=d --name-only | while read filename; do run_swiftlint "${filename}"; done
git diff --cached --diff-filter=d --name-only | while read filename; do run_swiftlint "${filename}"; done
else
echo "${SWIFT_LINT} is not installed."
exit 0
fi
END_DATE=$(date +"%s")
DIFF=$(($END_DATE - $START_DATE))
echo "SwiftLint took $(($DIFF / 60)) minutes and $(($DIFF % 60)) seconds to complete."

This script provides the rules to work on the changes made in the files. By this way, we able to use the code style on the project we work on.

--

--

Çağatay Emekci
Mobile Development

iOS Application Developer, Opsgenie at Atlassian @CagatayEmekci