0

I am from Objc background & new to swift.

What does this comment means "/// Used in a static manner"

/// Used in a static manner
struct RecentItemsController {
    fileprivate init() { }
}

DO I really need this init()?

In the whole code base I have not written RecentItemsController(), then why need this constructor definition?

user804417
  • 155
  • 2
  • 13

1 Answers1

0

The fileprivate guarantees that you can't instantiate new objects from this class. So this is not possible:

let recentItemsController = RecentItemsController()

Note: the '()'.

I assume it was intended to be used as a singleton.

That's what's makes it static, and that's why you have never have written or find a new instantiation of this class.

You should have a shared instance of this static class along the lines of this in your RecentItemsController class:

static let sharedRecentItemsController = RecentItemsController()

and use that instance everywhere it's needed like so:

let recentItemsController = RecentItemsController.sharedRecentItemsController

which guarantees that you use the same object everywhere in your code (hence, static).

extra info:

fileprivate is almost the same as just a regular private attribute, which contains it in that class, but makes it useable in extensions.

Also read more on static and singleton classes in this nice blogpost here

Edit

I thought i'd add this: It could also be that the init is set to private to absolutely guarantee that no new instance can be made of the struct because structs provide a memberwise initializer:

Structure types automatically receive a memberwise initializer if they do not define any of their own custom initializers. Unlike a default initializer, the structure receives a memberwise initializer even if it has stored properties that do not have default values. - Apple Developer, section: Memberwise Initializers for Structure Types

So if you were actually using it as a Singleton it would be better to use a class than a struct.

VetusSchola
  • 41
  • 1
  • 5