Swift 3.0 Static instances, change in syntax from migration tool
本问题已经有最佳答案,请猛点这里访问。
在类中,我以前会创建这样的共享实例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class MenuConfigurator { // MARK: Object lifecycle class var sharedInstance: MenuConfigurator { struct Static { static var instance: MenuConfigurator? static var token: dispatch_once_t = 0 } dispatch_once(&Static.token) { Static.instance = MenuConfigurator() } return Static.instance! } } |
似乎Swift 3.0迁移工具已将代码块更改为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | class MenuConfigurator { private static var __once: () = { Static.instance = MenuConfigurator() }() // MARK: Object lifecycle class var sharedInstance: MenuConfigurator { struct Static { static var instance: MenuConfigurator? static var token: Int = 0 } _ = MenuConfigurator.__once return Static.instance! } } |
我得到了错误
在Swift 3中,
创建单例的推荐方法(至少自Swift2以来)是
1 2 3 4 5 6 | class MenuConfigurator { static let sharedInstance = MenuConfigurator() } let configurator = MenuConfigurator.sharedInstance |
忘记迁移者的建议。