开发中经常要讲到代码规范化,code review是一方面,另一方面可以借助一些工具,如Swift Format,做到代码格式化。
Swift Format
github地址 :https://github.com/nicklockwood/SwiftFormat
1 Swift Format 使用有四种方式,本文主要讲对第三种build phase的改进方式。
That depends. There are four ways you can use SwiftFormat:
1 As a command-line tool that you run manually, or as part of some other toolchain
2 As a Source Editor Extension that you can invoke via the Editor > SwiftFormat menu within Xcode
3 As a build phase in your Xcode project, so that it runs every time you press Cmd-R or Cmd-B, or
4 As a Git pre-commit hook, so that it runs on any files you've changed before you check them in
2 把脚本放在build phase,会引起的问题就是build之后才整理代码导致breakpoint失效,为了解决这个问题,把执行脚本时机放在pre-action,按下build的时候就会先格式化代码。
(1)pod引入Swift Foramt,Podfile设置如下,然后cd到工程路径,pod install
platform :ios, "11.0"
def app_pods
pod 'SwiftFormat/CLI', '0.40.4'
end
target 'TestFormat' do
app_pods
end
(2)Edit sheme->Build->Pre-action->New Run Script Action,添加脚本文件。
脚本文件内容如下:
if [ "${CONFIGURATION}" = "Debug" ]; then
"${PODS_ROOT}/SwiftFormat/CommandLineTool/swiftformat" --disable unusedArguments,numberFormatting,redundantReturn,andOperator,anyObjectProtocol,trailingClosures,redundantFileprivate --ranges nospace --swiftversion "5.0" "${SRCROOT}/TestFormat/"
echo "format debug build swift code"
else
echo "Not Debug Env, skip format"
fi
(3)写入不规范的代码,按下build进行测试。可以看到代码自动规范化了,再进行building。
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func test(){
let isTest = false
if isTest {
NSLog("testing")
}
else{
}
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func test() {
let isTest = false
if isTest {
NSLog("testing")
} else {}
}
}