kyzmitch
(Andrey Ermoshin)
1
Hello, is this a missing implementation, isn't it? I feel that it should be possible to use optional generic argument, but it is not. Is there a workaround for this?
here is an example of source code which doesn't compile.
protocol Dependency {}
protocol Interface {
associatedtype D: Dependency
func use(_ input: D)
}
struct SomeDependency: Dependency {}
class SomeImplementation: Interface {
typealias D = SomeDependency
func use(_ input: D) {
}
}
func handle<I: Interface>(_ interface: I?) where I.D == SomeDependency {
let dependency = SomeDependency()
interface?.use(dependency)
}
let input = SomeImplementation()
handle(input)
handle<SomeImplementation>(nil) // Cannot explicitly specialize a generic function
handle(nil) // Generic parameter 'I' could not be inferred
tera
2
try:
handle(nil as SomeImplementation?)
2 Likes
spadafiva
(Joe Spadafora)
3
You could probably do something like:
enum InterfaceHandler<I: Interface> {
static func handle<I>(_ interface: I?) where I.D == SomeDependency {
// ...
}
}
InterfaceHandler<SomeImplementation>.handle(nil)
I think this should work, but I haven't tried it
1 Like
This and handle(SomeImplementation?.none) are how to do it, with the code you have.
But usually when I see code like this, it's a sign that the optionality should be moved outward.
if let implementation = SomeImplementation() as Optional {
handle(implementation)
}
func handle(_ interface: some Interface<SomeDependency>) {
interface.use(.init())
}
2 Likes