I'm defining a Singleton with this code:
class MySingleton {
static let instance = MySingleton()
private init() {}
func example(myParameter:String) {
}
}
Which seems to work ok as I can do the following call correctly:
MySingleton.instance.example(myParameter:"a string")
The strange behavior is that I can also do this one:
MySingleton.example(self: MySingleton.instance)
I know I have defined a static property to create the Singleton but the function example
is not static, so why can I call it from class level? Also, notice the parameter of this second call, it is not receiving the String
parameter defined in the function but a self
of type MySingleton
.
As I have seen this doesn't happen if the function is defined as private, but obviously I need it public for proper use so, what am I defining wrongly?
Although it has been said that this question is already answered in SO I think there are some differences that make this one unique and that's why I'm going to answer it.
My implementation of the Singleton is totally correct and the problem that was concerning me is described, as Martin R has said in the comments, here. It is known as “Curried” Functions, as that link will tell you far more than I can.
In regard to the singletons there's no way, as far as I have discovered, to hide these "class" methods. However, it is also true we shouldn't worry much about it as some official classes (the ones made by Apple) that uses singletons also show this same behavior. Here we have some examples in case you want to check:
So basically, if you're just making a singleton (and you aren't familiar with curried functions) and you see this behavior, don't worry about it, it is the correct way to do it and there's nothing wrong in your code.