0
2

【Swift】OptionSetという複数の値をまとめて管理できるものがあるらしい

Posted at

はじめに

デフォルトで用意されているコードスニペットを見ていたら使ったことのない機能を見つけたので使ってみました。
スクリーンショット 2023-11-21 22.35.43.png

サンプルアプリ

Simulator Screen Recording - iPhone 15 - 2023-11-21 at 22.34.58.gif

実装

import SwiftUI

struct ContentView: View {
    @State private var sectionOptions: SectionOptions = .none
    var body: some View {
        List {
            Section {
                Text("コンテンツ")
            } header: {
                if sectionOptions.contains(.showHeader) {
                    Text("ヘッダー")
                }
            } footer: {
                if sectionOptions.contains(.showFooter) {
                    Text("フッター")
                }
            }
            
            Button {
                sectionOptions = .none
            } label: {
                Text("none")
            }
            .disabled(sectionOptions == .none)
            
            Button {
                sectionOptions = .headerOnly
            } label: {
                Text("headerOnly")
            }
            .disabled(sectionOptions == .headerOnly)
            
            Button {
                sectionOptions = .footerOnly
            } label: {
                Text("footerOnly")
            }
            .disabled(sectionOptions == .footerOnly)
            
            Button {
                sectionOptions = .headerAndFooter
            } label: {
                Text("headerAndFooter")
            }
            .disabled(sectionOptions == .headerAndFooter)
        }
    }
}

struct SectionOptions: OptionSet {
    let rawValue: Int
    
    static let showHeader = SectionOptions(rawValue: 1 << 0)
    static let showFooter = SectionOptions(rawValue: 1 << 1)
    
    static let none: Self = []
    static let headerOnly: Self = [.showHeader]
    static let footerOnly: Self = [.showFooter]
    static let headerAndFooter: Self = [.showHeader, .showFooter]
}

おわり

複数の状態を1つの値で持っておけるのは便利ですね

公式ドキュメント

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