Reputation: 20341
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.
Upvotes: 12
Views: 15825
Reputation: 955
struct
have the default member wise initialiser. Means if you don't provide any init
for struct then compiler automatically synthesise that for you. The default synthesised init
would be created like
init(member: Type, ...) {
/// Initialisation here.
}
So your struct with the automatically synthesised initialiser would look like ---
public struct MyStruct {
public let prop1: String
public let prop2: String
/// Auto generated init will be like
init(prop1: String, prop2: String) {
self.prop1 = prop1
self.prop2 = prop2
}
}
As you can see the property type is public
but the initialiser type is internal
so that is causing this issue. You can create initialiser that will fix it.
Upvotes: 1
Reputation: 1703
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.
Upvotes: 6
Reputation: 13675
you don't have to define the struct's properties as public,
just the initializer (public init) like this:
public struct MyStruct {
let prop1: String
let prop2: String
public init(prop1: String, prop2: String){
self.prop1 = prop1
self.prop2 = prop2
}
}
Upvotes: -1