Format Swift with a Git Commit Hook
Automatic Swift code formatting upon Git commitment can be achieved using the swift-format tool and Git pre-commit hooks. Xcode 16 includes swift-format in its toolchain, which can be executed via the command line like swift format MyFile.swift. Configuration for swift-format is managed through a .swift-format file, which the tool searches for in the current directory and successive parent directories. A default configuration can be generated using swift format dump-configuration, modified to define custom code styles, and stored in a preferred location. Git Hooks enable running custom scripts at specific actions, with a pre-commit hook executing before a commit is finalized. The provided pre-commit script uses git diff to identify staged Swift files (added, copied, modified, or renamed). It then runs swift format --in-place --parallel on these files, modifying them directly. Because the formatter changes the files, the script subsequently uses git add to restage the newly formatted files for commitment. This pre-commit script must be copied into the .git/hooks directory of each repository and made executable. Since this is a client-side hook, installation is necessary for every new or cloned repository. The pre-commit check can be bypassed using the git commit --no-verify command.