I am trying to use multiple files in SwiftUI playground. I added some code in a separate file in sources. I just want the sheet view to appear when the button is tapped. Even though I have made the struct public but I still get the error as " SecondView initializer is inaccessible due to internal protection level "
Here's the code:
struct ContentView: View {
@State private var showingScene = false
var body: some View {
Button(action: {
self.showingScene.toggle()
}, label: {
Text("Button")
})
.sheet(isPresented: $showingScene, content: {
SecondView()
})
}
}
//The code in source file
import SwiftUI
public struct SecondView: View{
public var body: some View {
Text("Second View")
}
}
The default initialiser (the one generated by the compiler, since you didn't declare one explicitly) is actually internal
.
This is documented here:
A default initializer has the same access level as the type it initializes, unless that type is defined as public. For a type that’s defined as public, the default initializer is considered internal. If you want a public type to be initializable with a no-argument initializer when used in another module, you must explicitly provide a public no-argument initializer yourself as part of the type’s definition.
So you should do:
public struct SecondView: View{
public init() { } // here!
public var body: some View {
Text("Second View")
}
}