I had this implementation with Swift 2.0 and the Xcode suggestion is not only baffling but causes compilation error as well. it\'s a library where users are passing callfunc
Create a singleTon class as follows :
class mySingleTon{
//1. gives you SingleTon object which is created only once.
static let sharedInstance = mySingleTon()
//2. make init private so it prevents others from using the default '()' initializer for this class.
private init(){
print("i am born")
}
func foo()
{
print("hello")
}
}
Example usage :
class A{
func bar()
{
mySingleTon.sharedInstance.foo()
//3. Uncomment to get error : initializer is inaccessible due to 'private' protection level.
// let newSharedInstance = mySingleTon()
}
let a = A()
let b = A()
a.bar()
b.bar()
Output :
i am born
hello
hello
As you noticed Initializer is only called once. As per apple docs :
dispatch_once to make sure that the initialization is atomic. This enables a cool way to use dispatch_once in your code: just declare a global variable with an initializer and mark it private.”Explaining Comments :
Static member of class implicitly calls "dispatch_once" hence it is thread safe.
Making init private prevents initialisation again.
Test code line to prove initialisation is private.