'Struct initializer is inaccessible due to private protection level from its own file

Using Swift 4, I have defined two structs in the same file, where one of them is private so this file is the only one that can access it. Also I'm relying on the struct's default/synthesized initializer i.e. I'm not explicitly defining one:

private struct A {
  private let string: String
  ...
}

struct B {
  func foo() {
    let a = A(string: "bar")
    ...
  }
}

However this will fail to compile with the following error:

'A' initializer is inaccessible due to 'private' protection level

I don't want to have A accessible to other files, so I tried to work around it by making it fileprivate (which should be equivalent to private in this scenario), but the same compilation error will occur (and it still complains that the protection level is private).

Is there a way to keep this struct fileprivate and still get a synthesized initializer that exposes all uninitialized properties? i.e. A.init(string:)



Solution 1:[1]

You can define initializer. It will help you to keep this structure private. The main problem is private let string compiler automatically add initializer with private access level private init(string: String).

For fix you have to define your own initializer

private struct A {
    private let string: String

    fileprivate init(string: String) {
        self.string = string
    }

    func foo() {}
}

struct B {
    func bar() {
        A(string: "baz").foo()
    }
}

Or you can use fileprivate access level for string property. In this case you don't need initializer.

private struct A {
    fileprivate let string: String

    func foo() {}
}

struct B {
    func bar() {
        A(string: "baz").foo()
    }
}

Solution 2:[2]

Here is another way to address the error which can happen when working with SwiftUI structs.

Given this code will produce the same error since the variable is not initialized or the compiler does not know if that variable is guaranteed to have a value.

struct MyView: View {
    // Compiler: ¯\_(?)_/¯ 
    // initializer is inaccessible due to 'private' protection level
    private var rows: [Int]

    var body: some View {
        Text("Some text")
    }
}

So you either make it optional, unwrapped or initialize with a value.

struct MyView: View {
    // Initialized
    private var rows = [Int]()

    var body: some View {
        Text("Some text")
    }
}

When MyView() is instantiated the compiler will not complain.

struct MyView_Previews: PreviewProvider {
    static var previews: some View {
        MyView()
    }
}

Solution 3:[3]

I Used

private let s: String = "Some value"

it works for me..

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 naz
Solution 3 jamal zare