objective-c - 推断为具有类型“()”的常量,这可能是意外的 - 在 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 中替换的正确方法吗?其次,我该如何处理这个警告?
解决方案
是的,这是您可以替换 dispatch_once 的方法之一。对于您的特定用例,您可以考虑将此代码放置在应用程序生命周期中只会执行一次的位置,这可能是您的用例的最佳方法。
如果您只想摆脱警告,可以将 executeStartup 的类型声明为 Any
let executeStartup : Any = {
self.executeUnsafeStartupWithConfig(config: MPConfig.config.configWithAppKey(appKey: appKey, withAppId: appId, withAccountId: accountId, forProduction: inProduction), authToken: authToken)
}()
推荐阅读
- java - Spring Kafka - 为任何主题的分区消耗最后 N 条消息
- java - 有没有办法将 Java 服务器中的 GraphQL 查询转换为 SPARQL 查询?
- java - 有什么方法可以知道 Android 上的 Parcel 中的对象类型是什么?
- git - K8S:如何通过 SSH 服务(Gitea)在同一主机上访问 pod,ingress-nginx 暴露为 HTTP?
- python - Groupby多年来每个月的最大值和最小值
- java - 如何从 eclipse e4 中的处理程序执行方法中获取图标
- javascript - JWT 验证错误:JsonWebTokenError: invalid algorithm
- equals - 两个字面上相同的 CGAL::Point_3 点之间不相等
- python-3.x - 数据提取到图形输出
- java - JUnit 5 @Tag does not work as expected with @BeforeEach/@AfterEach