Swift 3.0 单例 [英] Singleton with Swift 3.0

查看:33
本文介绍了Swift 3.0 单例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Swift 2.0 中实现了这个实现,Xcode 的建议不仅令人困惑,而且还会导致编译错误.这是一个用户传递 callfunc 闭包的库.

I had this implementation with Swift 2.0 and the Xcode suggestion is not only baffling but causes compilation error as well. it's a library where users are passing callfunc closures.

之前

protocol MyProtocol {

}

主类

private static var t: dispatch_once_t = 0
private static var singleton: MyProtocol?
public class func getSingleton(callfunc: () -> MyProtocol) -> MyProtocol {
    dispatch_once(&self.t) {
        self.singleton = callfunc()
    }
    return singleton!
}

之后

    private static var __once: () = {
        MyProtocol.singleton = callfunc()
    }()

    open class func getSingleton(_ callfunc: () -> MyProtocol) -> MyProtocol {
        singleton = MyProtocol.__once()
        return singleton!
    }

我基本上需要将参数传递给 __once 函数.

I basically need to pass parameter to __once function.

用户:

class Test: MyProtocol {

}

Main.getSingleton({Test()});

它不是 在 Swift 中使用 dispatch_once 单例模型的副本,正在传递一个闭包,它是一个 .framework,闭包是由库的用户传入的.

It's not a duplicate of Using a dispatch_once singleton model in Swift, a closure is being passed, it's a .framework and closure is passed in by the user of the library.

推荐答案

我通常喜欢这种模式:

final class MyClass {静态让共享 = MyClass()}

然后您可以调用 MyClass.shared 来获取您的单身人士.

Then you can call MyClass.shared to get your singleton.

这篇关于Swift 3.0 单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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