LoginSignup
2
4

More than 5 years have passed since last update.

Swiftのenum型の要素をindexで指定してStringで取得

Last updated at Posted at 2018-10-19

やりたかったこと

  • Iconのリストを表示したかった。
  • imageViewの表示にファイル名が必要なので、Assetsのファイル名をenumにしておいて、そのままStringでとりたかった

cell.imageView.image = UIImage(named: "ここにファイル名をEnumから入れたい ")

解決

Swift4.2 CaseIterableを使う + Stringを継承させる

CaseIterableで Icon.allCasesが使え、配列でEnumの要素を返してくれます。

(lldb) po Icon.allCases
▿ 3 elements
  - 0 : CheckBoxProject.Icon.apple
  - 1 : CheckBoxProject.Icon.game
  - 2 : CheckBoxProject.Icon.teeth

このままだと文字列にならないので、Stringを継承させ、rawValueで文字列に変換します。

結果以下のコードにしました。


enum Icon: String, CaseIterable {
    case apple
    case game
    case teeth
}

cell.imageView.image = UIImage(named: Icon.allCases[indexPath.row].rawValue)
2
4
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
2
4