Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton pattern in Swift 1.2

Tags:

swift

I have previously used the following singleton pattern:

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

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

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

Looking at the debugger while using this it seems like a lot of nested instances of the singleton class are created by the class constant:

Screenshot of debugger

But looking thru the allocations it seems that only one instance are created. I guess that means it's working correctly, but I'm not seeing the same behavior with the first pattern.

like image 530
Kristoffer Johansson Avatar asked Feb 19 '15 23:02

Kristoffer Johansson


1 Answers

What is happening here is that LLDB is showing to you the static data as if it was instance data.

Because it's static data, it does not exist "in the instance" the way normal instance data works, which causes LLDB to read memory that it should not and present it to you as if it was valid.

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

like image 153
Enrico Granata Avatar answered Sep 30 '22 13:09

Enrico Granata