在不使用 dispatch_once_t 的情况下转换 Swift 3 代码 [英] Converting Swift 3 code without use of dispatch_once_t

查看:32
本文介绍了在不使用 dispatch_once_t 的情况下转换 Swift 3 代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在迁移到 Swift 3 之前,我有以下代码:

Prior to migrating to Swift 3, I had the following code:

//Set up singleton object for the tracker
class func setup(tid: String) -> WatchGATracker {
    struct Static {
        static var onceToken: dispatch_once_t = 0
    }
    dispatch_once(&Static.onceToken) {
        _analyticsTracker = WatchGATracker(tid: tid)
    }
    return _analyticsTracker
}

我收到以下错误:

'dispatch_once_t' is unavailable in Swift: Use lazily initialized globals instead

显然,转换工具将代码转换成这样:

Apparently, the conversion tool converted the code to this:

 class func setup(_ tid: String) -> WatchGATracker {
    struct Static {
        static var onceToken: Int = 0
    }
    _ = WatchGATracker.__once
    return _analyticsTracker
}

并且在我班级的顶部,它添加了以下内容:

And at the top of my class, it added this:

private static var __once: () = {
        _analyticsTracker = WatchGATracker(tid: tid)
}()

但我仍然收到错误消息:

But I still get an error:

Instance member 'tid' cannot be used on type 'WatchGATracker'

tid 声明为:

fileprivate var tid: String

它曾经被声明为:

private var tid: String

我似乎不知道如何修复我的代码,有人有什么建议吗?

I cannot seem to figure out how to fix my code, does anyone have any suggestions?

推荐答案

我们都已经习惯了过于复杂的单例模式……现在其实很简单:

We've all gotten used to over-complicated singleton patterns... It's actually very simple now:

class WatchGATracker {
    static let sharedInstance = WatchGATracker()
    private override init() {}
}

来源:http://krakendev.io/blog/the-right-way-to-write-a-singleton

至于 setup() 函数,我同意上面@Rob Napier 的回答,但我会更进一步.如果你试图重新配置一个单身人士,你就错了.如果您有一些必需的设置参数,从一种用途到另一种用途不同,您应该创建单独的实例.

As for the setup() function, I agree with @Rob Napier above in his answer but I'll go a step further. If you're trying to reconfigure a singleton you're doing it wrong. If you have some required setup parameter that varies from one usage to another you should create separate instances.

也许您尝试重用某种连接性或其他功能会导致您走上单例路径,但如果是这种情况,您应该只将该功能提取到它自己的类中,并让这些可配置的实例共享 单身.

Maybe there's some kind of connectivity or other function you're trying to reuse that's leading you down the singleton path but if that's the case you should extract just that function to it's own class and let these configurable instances share that singleton.

/// Watch Connection singleton
class WatchConnection: NSObject  {
    static let sharedInstance = WatchConnection()
    private override init() {}

    func doSomething() {}
}

//Watch tracker class for each instance of a watch
class WatchGATracker {
    init(tid: String) {
        //do something useful
    }

    let connection = { WatchConnection.sharedInstance }()
}

let one = WatchGATracker(tid: "one")
one.connection.doSomething()

这篇关于在不使用 dispatch_once_t 的情况下转换 Swift 3 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆