💭

SwiftUIリファクタリング事例①

2023/06/15に公開

【リファクタリング前】

struct ContentView: View {
    var body: some View {
        TabView {
            Tab1View()
                .tabItem {
                    VStack {
                        Image(systemName: "1.circle")
                        Text("タブ1")
                    }
                }
                .tag(1)
            Tab2View()
                .tabItem {
                    VStack {
                        Image(systemName: "2.circle")
                        Text("タブ2")
                    }
                }
                .tag(2)
            Tab3View()
                .tabItem {
                    VStack {
                        Image(systemName: "3.circle")
                        Text("タブ3")
                    }
                }
                .tag(3)
            Tab4View()
                .tabItem {
                    VStack {
                        Image(systemName: "4.circle")
                        Text("タブ4")
                    }
                }
                .tag(4)
            Tab5View()
                .tabItem {
                    VStack {
                        Image(systemName: "5.circle")
                        Text("タブ5")
                    }
                }
                .tag(5)
        }
    }
}

【リファクタリング後】

struct ContentView: View {
    var body: some View {
        TabView {
            tabView(name: "ホーム",    icon: "house",               view: Tab1View(), tag: 1)
            tabView(name: "オプション", icon: "gearshape",           view: Tab2View(), tag: 2)
            tabView(name: "音楽",      icon: "music.note",          view: Tab3View(), tag: 3)
            tabView(name: "マイページ", icon: "person",              view: Tab4View(), tag: 4)
            tabView(name: "設定",      icon: "slider.horizontal.3", view: Tab5View(), tag: 5)
        }
    }
    
    @ViewBuilder
    private func tabView<V: View>(name: String, icon: String, view: V, tag: Int) -> some View {
        view
            .tabItem {
                VStack {
                    Image(systemName: icon)
                    Text(name)
                }
            }
            .tag(tag)
    }
}

Discussion