I have a Swift framework that defines a struct:
public struct CollectionTO { var index: Order var title: String var description: String }
However, I can't seem to use the implicit memberwise initialiser from another project that imports the library. The error is:
'CollectionTO' cannot be initialised because it has no accessible initialisers
i.e. the default synthesized memberwise initialiser is not public
.
var collection1 = CollectionTO(index: 1, title: "New Releases", description: "All the new releases")
I'm having to add my own init method like so:
public struct CollectionTO { var index: Order var title: String var description: String public init(index: Order, title: String, description: String) { self.index = index; self.title = title; self.description = description; } }
... but is there a way to do this without explicitly defining a public init
?
The memberwise initializer is a shorthand way to initialize the member properties of new structure instances. Initial values for the properties of the new instance can be passed to the memberwise initializer by name. The example below defines a structure called Size with two properties called width and height .
In Swift, all structs come with a default initializer. This is called the memberwise initializer. A memberwise initializer assigns each property in the structure to self. This means you do not need to write an implementation for an initializer in your structure.
When you mark public , the thing gets available outside of the framework in which your code has been implemented whereas init() {} is a swift initializer that is responsible for ensuring the object is fully initialized. Basically initializers are called to create a new instance of a particular type.
Designated Initializers and Convenience Initializers Swift defines two kinds of initializers for class types to help ensure all stored properties receive an initial value.
Quoting the manual:
"Default Memberwise Initializers for Structure Types The default memberwise initializer for a structure type is considered private if any of the structure’s stored properties are private. Otherwise, the initializer has an access level of internal.
As with the default initializer above, if you want a public structure type to be initializable with a memberwise initializer when used in another module, you must provide a public memberwise initializer yourself as part of the type’s definition."
Excerpt from "The Swift Programming Language", section "Access Control".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With