投稿の経緯
機械的にコードチェックをおこない、コードの統一化、可読性の向上、、開発効率の向上を期待してSwiftUIで開発中の個人アプリにはじめてSwiftFormat
を導入したので記事にしました。
環境
Swift version 5.4.2
Xcode version 12.5.1
SwiftFormatとは
公式ページには以下のように記載されています。
What is this?
SwiftFormat is a code library and command-line tool for reformatting Swift code on macOS or Linux.
SwiftFormat goes above and beyond what you might expect from a code formatter. In addition to adjusting white space it can insert or remove implicit self, remove redundant parentheses, and correct many other deviations from the standard Swift idioms.Why would I want to do that?
Many programmers have a preferred style for formatting their code, and others seem entirely blind to the existing formatting conventions of a project (to the enragement of their colleagues).
When collaborating on a project, it can be helpful to agree on a common coding style, but enforcing that manually is tedious and error-prone, and can lead to arguments if some participants take it more seriously than others.
Having a tool to automatically enforce a common style eliminates those issues, and lets you focus on the behavior of the code, not its presentation.
要約すると、self
や不要な空白の削除の修正を機械的におこなうライブラリであり、導入するメリットは、プログラマ個人のこだわった書き方でチーム開発をおこなうと、不要な議論が生まれて開発に集中できなくなるので、このツールを使ってチームでの共通化と自動修正を実現し、その問題を事前に防ぎましょう。
といったところでしょうか🤔
cocoaPodsでの導入
導入はCocoaPods
を選定しました。
👇以下理由👇
フォーマッターのインストールはhomebrewなどを使って各自の環境にインストールするという手段もあるが、複数人で開発を行う場合に、各自のインストールしているバージョンに違いが発生する恐れがる。
cocoaPodsにしておけばインストールされるバージョンが固定されるので意図しないバージョンが使われてしまうといった恐れがなくなるメリットがある。
pod 'SwiftFormat/CLI', :configurations => ['Debug']
pod install
して導入しましょう。
SwiftFormatを動かすPhaseを作る
Compile Sources
の前にRunscript
を作成し、SwiftFormatを動かすPhaseを作ります。
if [ $CONFIGURATION = "Debug" ]; then
"${PODS_ROOT}/SwiftFormat/CommandLineTool/swiftformat" .
fi
これは、SwiftFormatでコードを整形 > 整形された状態でコンパイルとする為です。
swiftversionの指定
このままだとSwiftFormatが、どのバージョンのSwiftに対してコードを整形したらいいかが分からないのでWarning
が発生します。なので、オプションに自身の環境で使用しているSwiftのバージョンを追加します。
--swiftversion 5.4.2
こちら👆を追記して
if [ $CONFIGURATION = "Debug" ]; then
"${PODS_ROOT}/SwiftFormat/CommandLineTool/swiftformat" . --swiftversion 5.4.2
fi
こうなればOKです。
オプションを追加する
swiftversionの指定で対応したように、他にもオプションを設定できます。
今回は
・PodsのソースをSwiftFormatの対象から外す
・ルールを無効にする
この2点をオプションとして追加してみたいと思います。
PodsのソースをSwiftFormatの対象から外す
Podsのソースは直接触ることがないので、整形の対象がら外します。
--exclude Pods
こちらを追記します。
ルールを無効にする
SwiftFormatにはルールが存在し、ルールに従いたくない場合にオプションを追加します。
このルールを無効化したい場合は、--disable ルール名
で無効化できます。
例えば、andOperator
を無効化したい場合は
--disable andOperator
これで無効化できます。
各オプションを反映するとSwiftFormatを動かすPhaseは👇以下のようになります。
if [ $CONFIGURATION = "Debug" ]; then
"${PODS_ROOT}/SwiftFormat/CommandLineTool/swiftformat" . --exclude Pods --swiftversion 5.4.2 --disable andOperator
fi
これでビルド完了後にSwiftFormatが動作します!
参考にしてください。
お知らせ
現在、iOS開発案件を業務委託で募集中です(副業)。TwitterDMでご依頼をお待ちしています。