-4

How write singleton class setup in swift 3.0. Currently i am using this code in objective c . How write singleton class setup in swift 3.0. Currently i am using this code in objective c

 #pragma mark Singleton
static ModelManager* _instance = nil;

+ (ModelManager *) sharedInstance {
@synchronized([ModelManager class]){
    if (!_instance) {
        _instance = [[self alloc] init];
    }
    return _instance;
}
return nil;
}
+ (id)alloc {
@synchronized([ModelManager class]){

    NSAssert(_instance == nil, @"Attempted to allocate a second instance of a singleton.");
    _instance = [super alloc];
    return _instance;
}
return nil;
}
+ (id)allocWithZone:(NSZone *)zone {
@synchronized([CTEModelManager class]) {
    NSAssert(_instance == nil, @"Attempted to allocate a second instance of a singleton.");
    _instance= [super allocWithZone:zone];
    return _instance; // assignment and return on first allocation
}
return nil; //on subsequent allocation attempts return nil
}
- (id)init {
self = [super init];
if (self != nil) {
}
return self;
}
- (id)copyWithZone:(NSZone *)zone {
return self;
}
vikramarkaios
  • 301
  • 1
  • 13
  • 1
    There is also a "Singleton" section in [Adopting Cocoa Design Patterns](https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/AdoptingCocoaDesignPatterns.html#//apple_ref/doc/uid/TP40014216-CH7-ID6). – Martin R Jun 20 '17 at 11:19

1 Answers1

2

Apple finally took care of that, it's this simple ...

open class Grid {
    static let shared = Grid()
    

As a rule (you can google endless discussion on this), you add

open class Grid {
    static let shared = Grid()
    fileprivate init() {}

That's all there is to it.

To use the singleton you simply "Name.shared", so

 x = Grid.shared.someFunction()

The "pure sugar" idiom...

Consider this: Any reason not use use a singleton "variable" in Swift? addition. Be aware it is pure syntactic sugar, or perhaps cocaine, and may or may not be right for you.

Community
  • 1
  • 1
Fattie
  • 27,874
  • 70
  • 431
  • 719
  • class SingletonClass: NSObject { static let sharedInstance = SingletonClass() func isValidEmail(_ testStr:String) -> Bool { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}" let range = testStr.range(of: emailRegEx, options:.regularExpression) let result = range != nil ? true : false return result } } – Vibha Singh Jun 20 '17 at 11:23
  • 1
    hi @VibhaSingh. you need to ask a new, separate question for that. Cheers. – Fattie Jun 20 '17 at 11:25