在 SwiftUI playground 中使用多个文件

Using multiple files in SwiftUI playground

我正在尝试在 SwiftUI playground 中使用多个文件。我在源代码的单独文件中添加了一些代码。我只想在点击按钮时显示 sheet 视图。即使我已经创建了结构 public 但我仍然收到错误消息“由于内部保护级别,SecondView 初始值设定项无法访问”

代码如下:


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")       

    }
}

默认初始化程序(编译器生成的初始化程序,因为您没有明确声明)实际上是 internal

这已记录在案 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.

所以你应该这样做:

public struct SecondView: View{

    public init() { } // here!
    
    public var body: some View {

        Text("Second View")

    }
}