首页 > 解决方案 > 推断为具有类型“()”的常量,这可能是意外的 - 在 Swift 中替换 dispatch_once

问题描述

我的主要问题围绕着dispatch_once. 我在Swift中转换这个Objective-C代码:

dispatch_once(&_startupPred, ^{
        [MPPush executeUnsafeStartupWithConfig:[MPConfig configWithAppKey:appKey withAppId:appID withAccountId:accountId forProduction:inProduction] authToken:authToken];
    });  

Swiftify 并没有多大帮助。所以我挖得更深一些。显然 dispatch_once 不再在 Swift 中了。根据这个公认的答案,我可以通过以下方式实现:

let executeStartup = {
            self.executeUnsafeStartupWithConfig(config: MPConfig.config.configWithAppKey(appKey: appKey, withAppId: appId, withAccountId: accountId, forProduction: inProduction), authToken: authToken)
        }()

_ = executeStartup  

但是这样做,我收到了这个警告:

常量“executeStartup”推断为“()”类型,这可能是意外的

那么首先,这是dispatch_once在 Swift 中替换的正确方法吗?其次,我该如何处理这个警告?

标签: objective-cswiftgrand-central-dispatch

解决方案


是的,这是您可以替换 dispatch_once 的方法之一。对于您的特定用例,您可以考虑将此代码放置在应用程序生命周期中只会执行一次的位置,这可能是您的用例的最佳方法。

如果您只想摆脱警告,可以将 executeStartup 的类型声明为 Any

let executeStartup : Any = {
        self.executeUnsafeStartupWithConfig(config: MPConfig.config.configWithAppKey(appKey: appKey, withAppId: appId, withAccountId: accountId, forProduction: inProduction), authToken: authToken)
    }()

推荐阅读