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

1

2 Answers 2

3

It's so simple in Swift:

class YourClass {
    static let sharedInstance = YourClass()
}

and to use it:

YourClass.sharedInstance
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Boss! Working Now
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.