Singleton template in Swift 1.2

Earlier, I used the following singleton pattern:

class Singleton { class var sharedInstance : Singleton { struct Static { static let instance : Singleton = Singleton() } return Static.instance } } 

When the new beta version of Xcode with Swift 1.2 was released, I wanted to try new properties and methods of a static class. So I tried something similar to this:

 class Singleton { static let sharedInstance : Singleton = Singleton() } 

Looking at the debugger when using this, it seems that many nested instances of the same singlet class are created by the class constant:

Screenshothot of debugger

But, looking through the distribution, it seems that only one instance is created. I assume this means that it works correctly, but I do not see the same behavior with the first pattern.

+8
swift
source share
2 answers

What happens here is that LLDB shows you static data, as if it were instance data.

Since this is static data, it does not exist “in an instance”, how a normal instance of data works, which causes LLDB to read memory that it should not, and present it to you as if it were valid.

In general, the debugger should not show static data inside instances (compare the equivalent C ++ and how LLDB represents it).

+4
source share

You can check swift 1.2 single ton that your code is correct. No need to declare Singleton.

static let sharedInstance = Singleton ()

0
source share

All Articles