Travis Griggs
Travis Griggs

Reputation: 22252

how to squelch "result not used" warnings

In Swift2.2, I have an extension to Optional that looks like:

extension Optional {
    func ifNotNil<T>(_ closure:(Wrapped) -> T) -> T? {
        switch self {
        case .some (let wrapped):
            return closure(wrapped)
        case .none:
            return nil
        }
    }
}

It allows for code like

anImageView.image = self.something.ifNotNil { self.getImageFor($0) }

But sometimes, I don't care about the result:

myBSON["key"].string.ifNotNil {
    print($0}
}

In Swift2.2, it worked like a charm. But firing up the new XCode8 Beta and converting to Swift3, I'm getting warnings anywhere that I do the second type. It's almost as if there's an implicit @warn_unused_result. Is this just an early beta bug? Or something I can no longer do in Swift3? Or something I need to newly fix in Swift3?

Upvotes: 4

Views: 1232

Answers (1)

Guilherme Torres Castro
Guilherme Torres Castro

Reputation: 15350

You can discard the result using:

_ = myBSON["key"].string.ifNotNil {
    print($0}
}

Or mark your method to not warn for unused results:

extension Optional {

    @discardableResult func ifNotNil<T>(_ closure:(Wrapped) -> T) -> T? {
        switch self {
        case .some (let wrapped):
            return closure(wrapped)
        case .none:
            return nil
        }
    }
}

Reference : SE-0047

Upvotes: 9

Related Questions