R.swiftを使ってみる

便利とは聞いていたが、実務での使用経験がなかったため試してみる。

github.com

メリット

  • コード補完でリソースファイルにアクセスできる
  • 文字列による指定をしなくてよくなるのでtypoに気がつける

導入

R.swift(4.0.0)を導入していきます。
ドキュメント通りですが一応

CocoaPodsでインストール

pod 'R.swift'

Run Scriptの設定

Target > Build Phases を選択して Run Script を追加します。

"$PODS_ROOT/R.swift/rswift" generate "$SRCROOT"

追加したRun ScriptはCompile SourcesCheck Pods Manifest.lock間にドラックして動かしましょう。

f:id:y-hryk:20180802150223p:plain

R.generated.swiftをプロジェクトに追加する

上記の作業を終えたら一回ビルドします。
そうするとR.generated.swiftがプロジェクトのルートディレクトリに追加されているので、このファイルをプロジェクトに追加します。

ビルドされるたびにリソースの状態をみてR.generated.swiftが更新されるので .gitignoreに以下を追加します。

*.generated.swift

使用方法

let string = NSLocalizedString("localize_text", comment: "")
let image = UIImage(named: "sample")
let vc = UIStoryboard(name: "main", bundle: nil).instantiateInitialViewController()
tableView.register(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: "CustomCell")
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell

// R.swiftを使用
let string = R.string.localizable.localize_text()
let image = R.image.sample()
let vc = R.storyboard.main.instantiateInitialViewController()
tableView.register(R.nib.customCell)
let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.customCell, for: indexPath)!