Search code examples
swift

Initializer is inaccessible due to 'internal ' protection level


I have a struct defined in Swift with public properties

public struct MyStruct {
   
    public let prop1: String
    public let prop2: String
}

In my code, I try to initialize the struct by doing

MyStruct(prop1: "abc", prop2: "def")

But I get complier error saying 'MyStruct initializer is inaccessible due to 'internal protection' level.

The struct and member are in public protection level. So I don't understand what is 'internal' protection level.


Solution

  • First there are five different protection levels: private, fileprivate, internal, public and open.

    Any property, func or initializer you declare without a protection level keyword will automatically be declared as internal.

    Internal means, that your property, method or initializer is accessible everywhere within the same module.

    It seems like you are trying to create a new struct out of another module. Best solution would probably be to create your own init instead of the automatically generated one and declare it also as public.

    Hope this helps you.