As your team grows different developer can have different format of coding. Which sometimes can be difficult to read if there is no consistency.
So having a tool to enforce a common style of coding that lets you focus on the behavior of the code, not its presentation.
SwiftFormat
SwiftFormat is a code library and command-line tool for reformatting Swift code on macOS / Linux.
Is SwiftFormat different from SwiftLint?
SwiftLint is used to find and report bad code and style violations in your code. SwiftFormat is designed to fix them.
Installation
There are many ways to install it but the most been used is the terminal command and the Xcode extension. For the simplicity I will explain the Xcode extension
Xcode editor extension
$ brew cask install swiftformat-for-xcode
This will install SwiftFormat for Xcode in your Applications folder. Double-click the app to launch it, and then follow the on-screen instructions.
You also directly download the source and unzip the folder
SwiftFormat for Xcode.app
into your Applications
folder.
Now restart Xcode and will find SwiftFormat option under Xcode’s Editor menu.
Configuration
Its divided between rules and options.
Rules
Rules are functions in the SwiftFormat library that apply changes to the code.
There are different RULES which can be found in the link. Its updated often so to do check the list.
Options
Options are settings that control the behavior of the rules.
Lint — Adding Formatter in Build Phase
We can add the formatter in build phase so it works as a Lint.
Using Cocoapods
1. Add the SwiftFormat CLI to your Podfile
pod 'SwiftFormat/CLI'
Its install the pre-built command-line app.
2) Add a Build phase to your app target
a. Click on your project in the file list, choose your target under TARGETS, click the Build Phases tab
b. Add a New Run Script Phase by clicking the little plus icon in the top left .
c. Drag the new Run Script phase above the Compile Sources phase, expand it and paste the following script:
"${PODS_ROOT}/SwiftFormat/CommandLineTool/swiftformat" "$SRCROOT"
I hope you enjoyed the summary of SwiftFormatter.
References