In Swift, one should use type of parameters or return value to implicitly specialize a generic function. The problem is, when I call function like this:
func serialize<T>(continuation: GenericWithLongName<T, NSError> -> Void) -> Void
I cannot just write
serialize<SomeType> {
obj in
...
}
It should be
serialize {
(obj: GenericWithLongName<SomeType, NSError>) -> Void in
...
}
which looks painful.
It seems this "feature" exists for a long time. Is it a design decision? Is there any negative implication from allowing explicitly specialization?
And is there any way to make code above neat and clean without refactoring that generic class?
A generic function is a function that is declared with type parameters. When called, actual types are used instead of the type parameters.
Solution. A generic function that you might need to use explicit specialization is the one that infer its type from return type—the workaround for this by adding a parameter of type T as a way to inject type explicitly. In other words, we make it infer from method's parameters instead.
One way to "specialize" the function is by including the generic type as a function parameter:
func serialize<T>(
t: T.Type,
continuation: GenericWithLongName<T, NSError> -> Void ) -> Void { }
Now you can "specialize" the function like this:
serialize(SomeType.self) {
obj in
...
}
I don't know the answer to why your requested feature is not available. I agree that the feature you recommend would be useful, but in the meantime this works just as well and is almost as concise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With