0

I'm new to swift programming and please tell me how to implement singleton class in swift with code.

in obj-c I Know

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

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

How is it in swift

SUDHAKAR RAYAPUDI
  • 549
  • 1
  • 9
  • 18
  • Follow this url for singleton class http://codereview.stackexchange.com/questions/80246/swift-1-2-singleton-implementation – Lalit kumar Nov 17 '15 at 13:49

2 Answers2

3

It's so simple in Swift:

class YourClass {
    static let sharedInstance = YourClass()
}

and to use it:

YourClass.sharedInstance
Drizztneko
  • 161
  • 7
1

Swift is lot smarter than Obj-C about singleton class. You can declare like this;

final class MediaModel: NSObject {

    static let sharedMyManager = MediaModel()

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

Then call it;

let sharedManager = MediaModel.sharedMyManager
Kemal Can Kaynak
  • 1,638
  • 14
  • 26