Swift单例的写法

我们知道在Objective-C中我们经常这样去写单例

@implementation SXDataManager

static SXDataManager *sharedInstance = nil;

+ (SXDataManager*)sharedInstance
{
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

@end

而在Swift中我们经常这样去写单例

class SXDataManager : NSObject {

    class var sharedInstance: SXDataManager {
        struct Static {
            static var instance: SXDataManager?
            static var token: dispatch_once_t = 0
        }

        dispatch_once(&Static.token) {
            Static.instance = SXDataManager()
        }
        return Static.instance!
    }

}

你可能感兴趣的:(单例,swift)