Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 269
Travis Griggs Avatar asked Jan 05 '23 21:01

Travis Griggs


1 Answers

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

like image 195
Guilherme Torres Castro Avatar answered Jan 17 '23 08:01

Guilherme Torres Castro