I saw a number of references to using private init
in Swift to restrict object construction (e.g. this), yet it does not seem to be possible when I try (in Xcode 7.2.1 Playground):
class C {
private init() {}
}
var c = C() // No errors.
Am I missing something or is this actually a bug?
The default memberwise initializer for a structure type is considered private if any of the structure's stored properties are private. Likewise, if any of the structure's stored properties are file private, the initializer is file private. Otherwise, the initializer has an access level of internal.
Note: Swift Optional is not a stored properties. Hence, they need not be initialized. Stored properties are accessed inside the init() method using self property. Note: self is used to refer to the current instance within its own instance methods (Similar to this in java).
This is called class inheritance or subclassing, the class you inherit from is called the “parent” or “super” class, and the new class is called the “child” class. For safety reasons, Swift always makes you call super. init() from child classes – just in case the parent class does some important work when it's created.
You're probably expecting private
to restrict the use to within the class definition, but that's not what it does.
The definition of private
is to "restrict the use of an entity to its own defining source file".
From the Swift book, "Access Control" chapter.
EDIT:
As of Swift 3 fileprivate
does what private
used to and private
is now more restrictive in that it "restricts the use of an entity to the enclosing declaration"
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