swift项目用SwiftFormat自动格式代码

1. 安装 swiftformat
brew install swiftformat
2. 安装 swiftformat Xcode插件
brew install --cask swiftformat-for-xcode
3. 打开swiftformat

在程序坞中直接打开

open "/Applications/SwiftFormat For Xcode.app"

会看到 About, 介绍了 How do I install it?

4. 开启权限

设置->隐私与安全性->扩展
选择Xcode Source Editor,勾选SwiftFormat

5. 重启Xcode

点击 顶部 Editor目录可以看到 SwiftFormat, 可以手动格式化单个文件或选中内容

6. 配置快捷键

参考 https://www.jianshu.com/p/69883f2a16e1

7. 格式化代码

在项目目录批量格式化可以执行

swiftformat .

单个文件

swiftformat path/file.swift
8. 自动格式化代码

8.1 创建钩子目录

mkdir -p .git/hooks

8.2 创建 pre-commit 钩子脚本

cd .git/hooks
touch pre-commit

8.3 编辑 pre-commit 脚本

#!/bin/bash

# Get the staged Swift files
files=$(git diff --cached --name-only --diff-filter=ACM | grep '\.swift$')

# Check if any Swift files are staged
if [[ -n $files ]]; then
  # Format the staged Swift files using swiftformat
  swiftformat $files --swiftversion 5

  # Add the formatted files to the staging area
  git add $files
fi

8.4 赋予执行权限

chmod +x pre-commit

完成以上步骤,提交代码的时候会自动format

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容