[swift-users] Non-escaping closure not allowed to do let initialization?

Shawn Erickson shawnce at gmail.com
Thu Feb 2 14:33:18 CST 2017


I attempted the following code which involves passing a closure – one that
doesn't escape obviously – but the compiler complains that I need to make
formHeaders and formStream vars.

    public func finish() throws -> ([String:String],InputStream) {
        let formHeaders: [String:String]
        let formStream: InputStream
        try finish({ (fh, fs, _) in
            formHeaders = fh
            formStream = fs
        })
        return (formHeaders, formStream)
    }

If I have code like this however the use of let is ok.

    public func finish() throws -> ([String:String],InputStream) {
        let formHeaders: [String:String]
        let formStream: InputStream
        if self.finalized.get() {
            formHeaders = ["foo":"bar"]
            //formStream = ...
        }
        else {
            formHeaders = [:]
            //formStream = ...
            // or throw something here
        }
        return (formHeaders, formStream)
    }

If the closure is non-escaping and the code as structured the compiler
should be able to reason about the initialization correctness of those
lets...? ...or am I missing something?

-Shawn
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170202/846cf4b4/attachment.html>


More information about the swift-users mailing list