@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 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?

4
Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article