You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中@escape参数应添加在何处?解决闭包逃逸报错问题

Hey there! Let’s figure out how to fix this closure escape error you’re hitting in your Swift code.

What’s Causing the Error?

The core issue here is that you’re passing the fulfill and reject closure parameters (which Swift treats as non-escaping by default) into another closure that runs asynchronously — the completion handler for self.GET.

Since network requests are async, that completion handler won’t run until after the initial Promise setup closure finishes executing. This means fulfill and reject would "escape" their original scope, and Swift blocks this by default to prevent unintended memory issues or bugs.

How to Fix It

The fix depends on whether you’re using a custom Promise type or a third-party library like PromiseKit:

If You’re Using a Custom Promise Class

You need to mark the fulfill and reject parameters in your Promise initializer as @escaping. This tells Swift it’s okay for these closures to be stored and called later, outside their original scope.

Here’s how to update your Promise definition:

class Promise<T> {
    // Add @escaping to both closure parameters in the init
    init(_ handler: (@escaping (T) -> Void, @escaping (Error) -> Void) -> Void) {
        // Your existing Promise implementation logic here
        handler(/* Your fulfill closure implementation */, /* Your reject closure implementation */)
    }
}

Once you make this change, your original promisedGET method will work as written — the compiler will now allow fulfill and reject to be used in the async GET completion handler.

If You’re Using a Third-Party Promise Library (e.g., PromiseKit)

If you’re using a mature library like PromiseKit, its Promise type already handles escaping closures correctly. You might just need to adjust your syntax to match the library’s conventions. For example, PromiseKit uses a Seal object instead of separate fulfill/reject closures:

public func promisedGET<T: YumiInitializableFromJSON>(_ path: String, parameters: Alamofire.Parameters? = nil) -> Promise<T> {
    return Promise { seal in
        self.GET(path, parameters: parameters) { result in
            result.propagate(toFulfillment: seal.fulfill, rejection: seal.reject)
        }
    }
}

This should resolve the escape error without needing to manually add @escaping yourself.

内容的提问来源于stack exchange,提问作者JulienHora

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:41:18