Nitish
Nitish

Reputation: 14113

Constant inferred to have type '()', which may be unexpected - Replacing dispatch_once in Swift

My main issue revolves around dispatch_once. I am converting this objective-c code in Swift :

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

Swiftify doesn't help much. So I dig a bit deeper. Apparently dispatch_once is no longer in Swift. As per this accepted answer, I can achieve this by :

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

_ = executeStartup  

But by doing so, I get this warning :

Constant 'executeStartup' inferred to have type '()', which may be unexpected

So first, is this the correct way of replacing dispatch_once in Swift ? Secondly how do I handle this warning ?

Upvotes: 0

Views: 310

Answers (2)

Kamran
Kamran

Reputation: 15248

This will definitely execute the block once and you can specify the type as Void so that compiler does not complain.

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

You can also use lazy var executeStartup: Void as this will also ensure the block is executed once.

Upvotes: 1

nishith Singh
nishith Singh

Reputation: 2998

Yes this is one of the ways you can replace dispatch_once. For your specific use case you can consider placing this code where it will only be executed once in the lifecycle of the app, which is probably the best approach for your use case.

If you just want to get rid of the warning you can declare the type of executeStartup as Any

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

Upvotes: 1

Related Questions