0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Swift】ForEachにenumを使って繰り返し表示

Last updated at Posted at 2025-10-21

実現させること

  • enumの中にtitleTextという変数を保持しておき、ForEachの中で各casetitleTextを表示する
enum SectionTitle {
    case ALL
    case NORMAL
    case CHECKED
    case CURRENTLY_DETLETED
    
    var titleText: String {
        switch self {
        case .ALL: return "すべて"
        case .NORMAL: return "未達成"
        case .CHECKED: return "チェック済"
        case .CURRENTLY_DETLETED: return "最近削除した項目"
        }
    }
}

やること

1. enumCaseIterableに対応させる

  • allCasesプロパティに全てのcasesを集めることを許可する
enum SectionTitle: CaseIterable {

2. ForEach.allCasesを用いる

  • enumの各ケースのcollectionを集めてくれる
ForEach(SectionTitle.allCases, id: \.self) { title in

3. titleTextを呼び出す

  • い## 実現させること
  • enumの中にtitleTextという変数を保持しておき、ForEachの中で各casetitleTextを表示する
enum SectionTitle {
    case ALL
    case NORMAL
    case CHECKED
    case CURRENTLY_DETLETED
    
    var titleText: String {
        switch self {
        case .ALL: return "すべて"
        case .NORMAL: return "未達成"
        case .CHECKED: return "チェック済"
        case .CURRENTLY_DETLETED: return "最近削除した項目"
        }
    }
}

やること

1. enumCaseIterableに対応させる

  • allCasesプロパティに全てのcasesを集めることを許可する
enum SectionTitle: CaseIterable {

2. ForEach.allCasesを用いる

  • enumの各ケースのcollectionを集めてくれる
ForEach(SectionTitle.allCases, id: \.self) { title in

3. titleTextを呼び出す

  • イテレーション変数にtitleを用いてるので、title.titletextとなる
Text(title.titletext)

補足

  • caseの名前が英語の場合、公式はmapメソッドやjoinedメソッドを用いてcaseの名前を一文に連結し、連結した状態でそのままStringに格納するということを行っている。
enum CompassDirection: CaseIterable {
    case north, south, east, west
}


print("There are \(CompassDirection.allCases.count) directions.")
// Prints "There are 4 directions."
let caseList = CompassDirection.allCases
                               .map({ "\($0)" })
                               .joined(separator: ", ")
// caseList == "north, south, east, west"

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?