1

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.

2
  • 2
    Usually, factory methods are used, yeah. Commented Apr 4, 2016 at 22:09
  • looks strange in Objective-C, too. Commented Apr 5, 2016 at 8:23

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

All of the old Cocoa Objective-C inits were transformed into Swift class factories. Probably worth illustrating in your answer...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.