Tuesday, 10 June 2014

Swift Singletons

I've seen some questions flying around about how to write singletons in Swift and I thought I'd have a play to see what I could come up with. On the surface either of the first two techniques presented here appear to function as expected but with big gotchas. The third solution seems to achieved the desired aim, although they all suffer from an issue which I'll discuss at the end of this post.

Swift currently lacks any notion of public/protected/provide (one would assume this will come over time maybe) and also gives the developer no opportunity to define variables at class scope (statics) - using structs would appear to be a way around this and it is something which is explored in the code below.

Version 1 better represents the traditional Objective C approach (although the static is usually captured within the function - something we can't do here) - we do however expose the done and instance statics behind the implementation and these can be overwritten as shown in the test code.

Version 2 removes the requirement for the done but suffers from exactly the same problem as before in that the instance can be overwritten.

Version 3 seems to fix the ability to overwrite the underlying static and appears to achieve our stated goal.

So have we arrived at a solution?

What about if we now define these as 'global' variables
let v1 = MySingleton(123.45)
let v2 = MySingleton(234.56)
let v3 = MySingleton(345.67)

We've now got 3 separate instances - clearly not what we wanted.

I've seen this mentioned on the forums and originally suggested by Apple engineers as the solution to this problem. I guess it relies on convention and the developer only creating one such instance.

Until we can hide the initialiser then I guess we can't have a real solution to the problem (disclaimer - I haven't finished reading the language spec yet so perhaps something in there will help find a solution)

No comments:

Post a Comment