如何在Swift中实现Singleton类

时间:2015-11-17 13:46:08

标签: ios swift singleton

我是swift编程的新手,请告诉我如何使用swift在代码中实现单例类。

在obj-c中我知道

+ (id)sharedManager {
   static MediaModel *sharedMyManager = nil;
   static dispatch_once_t onceToken;

   dispatch_once(&onceToken, ^{
      sharedMyManager = [[self alloc] init];
   });
   return sharedMyManager;
}

如何快速

2 个答案:

答案 0 :(得分:2)

在Swift中这么简单:

class YourClass {
    static let sharedInstance = YourClass()
}

并使用它:

YourClass.sharedInstance

答案 1 :(得分:1)

Swift比Obj-C更聪明一些关于单身人士课程。你可以这样声明;

final class MediaModel: NSObject {

    static let sharedMyManager = MediaModel()

    private override init() {
        super.init()
    }
}

然后打电话给它;

let sharedManager = MediaModel.sharedMyManager