Swift创建单例

Objective-C使用GCD 中的dispatch_once_t 可以保证里面的代码只被调用一次,以此保证单例在线程上的安全。

但是在Swift 中由于废弃了原有的Dispatch once方法,因此无法使用once 进行单例的创建。

我们可以使用struct 存储类型变量,并且使用let保证线程安全的方式

(1)方案1

Swift 复制代码
class Manager {
    class var sharedManager: Manager {
        struct Static {
            static let sharedInstance: Manager = Manager()
        }
        return Static.sharedInstance
    }
}

(2)方案2

Swift 复制代码
class Manager {
    class var sharedManager: Manager {
        return sharedInstance
    }
}

private let sharedInstance = Manager()

(3)方案3

Swift 复制代码
class Manager {
    static let sharedInstance = Manager()
}
相关推荐
00后程序员张13 小时前
无需 Mac 的 iOS App 上架工具,开心上架Appuploader 负责哪些环节
android·ios·小程序·https·uni-app·iphone·webview
2501_9151063213 小时前
Windows 用 KXBuild 开发 iOS 项目,CocoaPods、SPM 怎么处理?
windows·vscode·ios·个人开发·swift·敏捷流程·cocoapods
2501_9159090614 小时前
KXApp 能打开哪些 iOS 项目?xcodeproj 与 CocoaPods 支持清单
ide·vscode·ios·个人开发·xcode·敏捷流程·cocoapods
开心就好20251 天前
uni-app 本地打包 iOS,在 Windows 上使用 KXBuild 产出 ipa 并上架的完整流程
后端·ios
调试人生的显微镜1 天前
跨平台抓包工具怎么选?TraceEagle抓包鹰 的四种跨平台能力
后端·ios
2501_915909061 天前
Ipa Guard 防护上架,混淆、重签名和回归测试怎么做
android·ios·小程序·https·uni-app·iphone·webview
木头分享1 天前
2026淘宝、京东双11活动全自动脚本丨IOS+安卓
ios
茶底世界之下1 天前
红花太抢眼,蓝天又想留下:用 Awaking 比较两种减饱和
ios
2501_916008891 天前
Windows 上写第一个 SwiftUI App,KXBuild 空工程起步,跑到 iPhone 真机
ide·vscode·ios·objective-c·个人开发·swift·敏捷流程
2501_915918411 天前
iOS 上架注意事项有哪些?Appuploader 的四个阶段自查清单
android·ios·小程序·https·uni-app·iphone·webview