LoginSignup
10
5

More than 1 year has passed since last update.

[SwiftUI]クラス・構造体とSwiftUIのコンポーネントの命名が被ってしまった場合

Last updated at Posted at 2021-12-06

クラス名や構造体の命名が、SwiftUIであらかじめ用意されているViewの命名と被ってしまった場合、
SwiftUI.使いたいViewで指定するで解決。

struct Menu {
    let label: String
    let icon: Image
}

struct MenuView: View {
    var body: some View {
        VStack{
            SwiftUI.Menu { // SwiftUI.Menuを追記
                ForEach(0..<5){ index in
                    Button(action: {}) {
                        Text("index: \(index)")
                    }
                }
            } label: {
                Image(systemName: "plus")
            }
        }
    }
}

NGな場合

以下のように、構造体やViewプロトコルに準拠させた自作のView構造体を作成する場合、再宣言が無効ですとエラーメッセージが吐き出されるされる。

Invalid redeclaration of 'MenuView'

struct MenuView: View {
    var body: some View {
        VStack{
            Menu {
                ForEach(0..<5){ index in
                    Button(action: {}) {
                        Text("index: \(index)")
                    }
                }
            } label: {
                Image(systemName: "plus")
            }
        }
    }
}

struct MenuView: View {
    var body: some View {
        Text("menuView")
    }
}

しかしながら、以下のような今回の事例では、異なるエラーメッセージが吐き出される


struct Menu {
    let label: String
    let icon: Image
}

struct MenuView: View {
    var body: some View {
        VStack{
            Menu {
                ForEach(0..<5){ index in
                    Button(action: {}) {
                        Text("index: \(index)")
                    }
                }
            } label: {
                Image(systemName: "plus")
            }
        }
    }
}

以下のエラーメッセージが発生する

  • Generic struct 'VStack' requires that 'Menu' conform to 'View'
  • Static method 'buildBlock' requires that 'Menu' conform to 'View'
  • Trailing closure passed to parameter of type 'Decoder' that does not accept a closure

Viewプロトコルに準拠させたViewの命名が被った場合は、このメッセージが表示されると思い込んでいたので、構造体同士がかぶっているとは、全く気づかなかった。。。
同じInvalid redeclaration of 'MenuView'で統一して欲しい。。。

10
5
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
10
5