Swift Format

Just-Tech-IT
Just-Tech-IT
Published in
2 min readMar 31, 2020

Par Benjamin DUMONT

Introduction

Swift format is a tool to reformat your Swift code using best practices.

Installation

Source Code & Documentation: https://github.com/apple/swift-format

To install it, get the source code and build it (be on the branch containing your Swift version). E.g. for Swift 5.1, use the following command lines:

Find your swift-format package (should be in .build/x86_64-apple-macosx/debug).

Get the path where the package is located and put it inside your path (e.g. inside your ~/.bash_profile) by adding this line (please adapt the path to your package):

To check if swift-format is in your path, please do the following commands:

Use inside Git Hooks

In pre-commit hook

Using this method will change your source code before committing. It means that you trust all changes made by swift-format. If not (it means that you don’t want to commit swift-format modifications before verifying them), please refer to the post-commit hook section.

Inside your workspace, edit/create a file .git/hooks/pre-commit and make sure that the files has execution rights using the command below:

Then, edit pre-commit file:

In post-commit hook

Using swift-format in post-commit hook let you verify swift-format actions before committing it. So you will have potentially 2 commits: one for your code and one for running swift-format. At the end of the commit, your workspace may have changes and you can decide which swift-format modifications to take by committing them (manually).

Inside your workspace, edit/create a file .git/hooks/post-commit and make sure that the files has execution rights using the command below:

Then, edit post-commit file:

Conclusion

There are many ways to use code formatters. You can use it in git phases or in build phases. Moreover, there are many formatters online. For instance, for Swift:

Find the one and the way that fits your usage.

👉 Auteur : Benjamin DUMONT

🔎 Lire les autres articles de Benjamin

--

--