1
2

More than 3 years have passed since last update.

SwiftGenをCocoaPodsで入れてみたよ

Posted at

SwiftGenをprojectに導入してみたので, 備忘録がてら書き残しておきます.
※SwiftGenはHomebrewを用いて導入することもできますが, 今回はCocoaPodsの場合のみです.
サンプルコードはこちら -> SwiftGenPractice
SwiftGen本家リポジトリはこちら -> SwiftGen(https://github.com/SwiftGen/SwiftGen)

目次

  1. CocoaPodsでSwiftGenをinstall
  2. swiftgen.ymlを用意
  3. BuildPhasesにSwiftGenに関する記述を追加

最終的に↓の画像のような構成になる前提で読んでいただけると.
スクリーンショット 2019-11-22 14.42.43.png

CocoaPodsでSwiftGenをinstall

Podfile
pod 'SwiftGen'

とりあえずPodfileにSwiftGenを記述して, pod install.
※CocoaPods自体の準備は割愛します.

swiftgen.ymlを用意

swiftgen.yml
xcassets:
  inputs:
    - ../Resources/Images.xcassets
    - ../Resources/Colors.xcassets
  outputs:
    - templateName: swift4
      output: ./Generated/Assets.swift

このように書くと, Image.xcassetsColors.xcassetsAssets.swiftに吐き出してくれます.

BuildPhasesにSwiftGenに関する記述を追加

任意のTarget(今回の場合だとSwiftGenPractice)のBuildPhasesののドリルダウンからNew Run Script Phaseを選びます.

あとはShellの中身に下記のように記述してビルドしたら出来上がりです.

$PODS_ROOT/SwiftGen/bin/swiftgen config run
--config $SRCROOT/SwiftGenPractice/SwiftGen/swiftgen.yml

ちなみに吐き出されたAssets.swift内にはこんな感じで書かれています.

Assets.swift
// MARK: - Asset Catalogs

// swiftlint:disable identifier_name line_length nesting type_body_length type_name
internal enum Asset {
  internal enum Colors {
    internal static let sampleColor = ColorAsset(name: "SampleColor")
  }
  internal enum Images {
    internal static let sampleImage = ImageAsset(name: "SampleImage")
  }
}
// swiftlint:enable identifier_name line_length nesting type_body_length type_name

staticな定数として宣言されているので, これらを使いたい時はAsset.Colors.sampleColorのようにして呼び出してやれば良いわけですね.
とても簡単ですしtypoもなくなるし最高ですね.

ダークモード対応でカラーアセットを使う機会も増えると思うので, SwiftGenも一緒に入れられると良いのではないでしょうか.

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2