Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does compiler warn of unused result on function marked @discardableResult?

Tags:

swift

The Swift 3 compiler is warning me of an unused result, even though I have marked the function with @discardableResult.

It is only occurring when calling the function on an optional variable, using the ? syntax.

To simplify the problem, I created this sample code. (I had to put it in a project because the warning didn't show in a playground.)

class Foo {
    @discardableResult func bar() -> String? {
        return "bar"
    }
}

class Tester {
    func doSomething() {
        var foo: Foo?

        foo = Foo()

        foo?.bar() //Warning: Expression of type 'String?' is unused
        foo!.bar() //No warning
    }
}
like image 242
Mike Taverne Avatar asked Dec 08 '25 08:12

Mike Taverne


1 Answers

It's a known bug (https://bugs.swift.org/browse/SR-1681), though the Swift gang seems to think it has been resolved. Maybe the fix hasn't made it into Xcode yet, or maybe they're just wrong.

UPDATE We got the official word: The fix will appear starting in Xcode 8.3.

like image 124
matt Avatar answered Dec 10 '25 22:12

matt