@Discardableresult Seems to Be Ignored in Protocols When Returning a Closure
Recently I Came Across an Issue When Designing Some of My Apis with @Discardableresult Applied to a Closure That Is Being Returned by Some Method. Protocols...
Recently I came across an issue when designing some of my APIs with @discardableResult applied to a closure that is being returned by some method. Protocols and classes I used to reproduce the issue are listed below.
SomeProtocol.swift:
// SomeProtocol.swift
protocol SomeProtocol {
@discardableResult func foo() -> () -> Void
}
SomeClass.swift:
// SomeClass.swift
class SomeClass: SomeProtocol {
@discardableResult func foo() -> () -> Void {
return {
print("foo")
}
}
}
And here's the use case:
let first = SomeClass()
first.foo() // No errors
let second: SomeProtocol = SomeClass()
second.foo() // "Function is unused" error
I've done a little bit of research and found this question, but it seems like it is not the case with the latest Swift versions anymore. I was unable to track down the version of Swift in which the error is gone, but in Swift 5.5.1 which I'm currently using there's the compiler error when method marked with @discardableResult required by a protocol returns a closure. There seem to be no errors when using a concrete type instead, as I mentioned in the use case.
Am I missing something or is it a Swift design choice?