Variable using only to keep a instance alive in unit test getting "only written to but never read" warning

Viewed 91

Here I'm using Quick to unit test part of my code, I declared the container variable to keep it alive outside the weaklyScpoed closure. Then I got the warning...

describe("foo") {
    it("bar") {
        // warning: variable "container" was written to, but never read
        var container: NSFPrioritizedDelegateContainer?
        let result = weaklyScoped(NSObject()) {
            container = NSFPrioritizedDelegateContainer.init(delegates: [$0], weakRef: true)
        }

        expect(result).to(beNil())
    }
}

the "weaklyScoped" function is also quite simple

func weaklyScoped<T: AnyObject>(_ v: @autoclosure () -> T, action: (T) throws -> ()) rethrows -> T? {
    weak var weakValue: T?
    do { // optionally autoreleasepool
        let value = v()
        try action(value)
        weakValue = value
    }

    return weakValue
}

How can I remove the warning and keep container alive outside the weaklyScoped closure?

1 Answers

Say

_ = container

That way you read its value harmlessly.

Related