diegomontoyas
diegomontoyas

Reputation: 1865

How to create multiple different initializers that take no parameters in Swift

In Objective-C we could have different initializers that did different things and took no arguments.

- (instancetype) initForSomethingSpecific;
- (instancetype) initWithDefaultSettings;

So you could call them as

[[MyClass alloc] initForSomethingSpecific];
[[MyClass alloc] initWithDefaultSettings];

These type of initializers get translated in Swift as

init(forSomethingSpecific: ())
init(defaultSettings: ())

so they can be called as

MyClass(forSomethingSpecific: ())
MyClass(defaultSettings: ())

but this doesn't look very swifty.

Is there a correct way to do this in a Swift-only environment? Are factory methods preferred?

Thank you.

Upvotes: 1

Views: 73

Answers (1)

GetSwifty
GetSwifty

Reputation: 7746

The factual side of this is there doesn't seem to be a way to do this with swift.

My personal understanding/opinion is the that purpose of an init method in Swift is to create an object with default characteristics, or with the information passed to it in the initializer. If you're instantiating an object for some specific configuration in an initializer, that's really a factory placed in an initializer, not a true initializer per se.

Upvotes: 2

Related Questions