I have been looking for a project that will really allow me to dive into the compiler and implement a new feature of some sort. Recently, I was writing a library to provide additional functionality to Combine called QuickCombine. During this process, I had the desire explicitly specialize the type of one of my generic functions, only to find out that this feature was missing from Swift.
After doing some research, I found that this had been discussed before on multiple occassions:
- Allow explicit specialization of generic functions (associated proposal)
- Proposal: Allow explicit type parameter specification in generic function call
Right now, one cannot explicitly specialize a generic function:
func foo<T>(_ value: T) { ... }
let specializedFoo = foo<Int> // Error: Cannot explicitly specialize a generic function
With generic function specialization, the code above would be valid and specializedFoo
would be of type (Int) -> Void
.
In Swift, we are currently allowed to specialize the generic type of an enum
, struct
, and class
; it seems only logical to extend this behavior to functions as well. In fact, the example above parallels the use of a typealias
when specializing a specific type (i.e. typealias IntArray = Array<Int>
).
As well, providing functions with the ability to explicitly specify their generic type parameters would allow us to lift the restriction wherein a generic type parameter must be used in the function signature. Currently, this is not allowed:
func typeOf<T>() -> String { // Error: Generic parameter 'T' is not used in function signature
return "\(T.self)"
}
Lifting this restriction would make functions like typeOf
valid, allowing it to be used in the following fashion:
print(typeOf<Int>())
// Prints "Int"
Implementation
To start off, I would like to try to implement this feature for just regular functions and initializers, ignoring subscripts and closures for now.
I have a few questions regarding the implementation of this feature:
- Is there any fundamental barrier that has prevented this from being added to Swift thus far or has no one tackled this issue yet?
- Where should I start when implementing this?
- What areas of the compiler would be affected by this?
- Any problems that a feature of this sort would introduce.
- Anything else important I should know regarding this feature.
- Any other advice for me when going about implementing this.
Before formally proposing or starting a discussion on a feature of this sort, I wanted to try and actually implement some of it first... so here I am .
All help is appreciated. Thank you!