Using swift-format to Lint and Format Swift Code
Ensuring a consistent code style in Swift projects is easy with swift-format. Here’s how to install and use it efficiently.
Ensuring a consistent code style in Swift projects is easy with swift-format. Here’s how to install and use it efficiently.
Installation
The simplest way to install swift-format is via Homebrew:
1
brew install swift-format
Usage
To lint and format all Swift files in your project, run:
1
swift-format -r -i .
Command Breakdown
swift-format: Executes the tool.-r(recursive): Formats all Swift files in the current directory and subdirectories.-i(in-place): Modifies files directly instead of printing formatted output..(current directory): Specifies the target directory. You can replace this with a specific file path if needed.
Custom Configuration
For finer control, create a .swift-format config file in your project root:
1
swift-format -m dump-configuration > .swift-format
Edit this JSON file to customize rules like line length, indentation, and formatting preferences.
Best Practices
- Run
swift-formatregularly to maintain code consistency. - Integrate it into your CI pipeline to enforce style guidelines automatically.
Using swift-format keeps your Swift code clean and uniform, making collaboration and maintenance easier! 🚀
☕ Support My Work
If you found this post helpful and want to support more content like this, you can buy me a coffee!
Your support helps me continue creating useful articles and tips for fellow developers. Thank you! 🙏