Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phlippieb/9564b095989056774064eb325a25d19f to your computer and use it in GitHub Desktop.
Save phlippieb/9564b095989056774064eb325a25d19f to your computer and use it in GitHub Desktop.
// Say you have a generic class with a couple of generic types,
// that also takes a couple of parameters in its initializer:
class Foo<T, U, V> {
init(label: String, other: Any) {
// ...
}
}
// Instantiating objects of this class in the standard way, while not unusual,
// can make for some ugly init code. The fact that the generic types aren't
// labeled make it unclear which types are required in which positions.
// There's also no nice way to format the types on separate lines.
let foo1 = Foo<MyClass1, MyOtherClass2, SomeExampleResultHandler>(label: "foo1", other: MyClass3.shared)
// We can make initializing much nicer with a factory:
class FooFactory {
func createFoo<T, U, V>(
inputType: T.Type,
outputType: U.Type,
resultHandlerType: V.Type,
label: String,
other: Any) -> Foo<T, U, V> {
return Foo<T, U, V>(label: label, other: other)
}
}
// ... which can then be used like this:
let foo2 = FooFactory.createFoo(
inputType: MyClass1.self,
outputType: MyOtherClass2.self,
resultHandlerType: SomeExampleResultHandler.self,
label: "foo2",
other: MyClass3.shared)
// The generic types have been from of the `<...>` part of the declaration,
// which is unlabeled and difficult to format,
// and to parameters for the factory method.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment