Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton class variable in swift? [duplicate]

I am trying to create a Singleton class, where I want to create an instance of UIImage.

In Objective-C

we can simple declare a property in .h like

@property (nonatomic,strong)UIImage *pic;

and define a sharedSingleton Method in .m

+(SingletonClass*)sharedSingleton{
  @synchronized(self){

   if (!sharedSingleton) {
       sharedSingleton=[[SingletonClass alloc]init];

   }
   return sharedSingleton;
}
}

and call from any class with

 [SingletonClass sharedSingleton].pic

I am searching from last 2 hours but didn't find ant suitable tutorial to create this. please help me out to create a singleton class in swift and tell me how to call the instance variable.

like image 377
M Swapnil Avatar asked Dec 25 '22 16:12

M Swapnil


1 Answers

its very simple in swift

class SharedManager {
   static let sharedInstance = SharedManager()
   var pic = UIImage()
}  

and to access it

SharedManager.sharedInstance.pic = UIImage(named: "imagename")! 

Here is very good guide about singleton

https://github.com/hpique/SwiftSingleton
https://thatthinginswift.com/singletons/

like image 181
EI Captain v2.0 Avatar answered Dec 27 '22 06:12

EI Captain v2.0