Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No more `private init` in Swift?

Tags:

swift

swift2

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?

like image 210
werediver Avatar asked Mar 11 '16 09:03

werediver


People also ask

What is private init in Swift?

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.

Do you need init class Swift?

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).

Why we use super init in Swift?

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.


1 Answers

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"

like image 133
Mike Pollard Avatar answered Sep 22 '22 15:09

Mike Pollard