A BLUE
A BLUE

Reputation: 33

about the Singleton pattern in Swift

here is a simple SingleTon pattern in Swift, it comes from:

https://github.com/hpique/SwiftSingleton

class Test {
    static let shareTest = Test()
    var a = 1
    init() {
        println("testSingeleTon")
    }
}

and here is a test function:

func testFunc() {

        var s1 = Test.shareTest
        var s2 = Test.shareTest
        var s3 = Test.shareTest
        var s4 = Test.shareTest

        func printPointer(pointer: UnsafePointer<Test>) {
            println(pointer)
        }

        printPointer(&s1)
        printPointer(&s2)
        printPointer(&s4)
        printPointer(&s3)

        println(s1.a)
        println(s2.a)
        println(s3.a)
        println(s4.a)

        s1.a = 4444

        println("s2.a = \(s2.a)")
        println("s3.a = \(s3.a)")
        println("s4.a = \(s4.a)")

    }

and what i confused is the result:

testSingeleTon
0x00007fff54432ad8
0x00007fff54432ad0
0x00007fff54432ac0
0x00007fff54432ac8
1
1
1
1
s2.a = 4444
s3.a = 4444
s4.a = 4444

it looks like a singleTon pattern, because just assign the value of s1.a, than the s2.a, s3.a, s4.a value had changed too, but, if it is a really singleTon pattern,why the &s1, &s2, &s3, &s4 are totally different??

0x00007fff54432ad8
0x00007fff54432ad0
0x00007fff54432ac0
0x00007fff54432ac8

Upvotes: 2

Views: 211

Answers (3)

Will M.
Will M.

Reputation: 1854

Each variable, s1, s2, s3, s4 hold a pointer to a Test object. Printing &s1 prints the location of that pointer, not the location of the object pointed to. If you want to print the address of an object that an object reference points to

println(unsafeAddressOf(s1))
println(unsafeAddressOf(s2))

etc.

source

source2 (Question I asked in order to figure this out better)

Upvotes: 1

Rasputin
Rasputin

Reputation: 487

Singletons before Swift 1.2 Thanks to Will M. for clarification.

class ActivityIndicator {

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

Upvotes: 0

LC 웃
LC 웃

Reputation: 18998

Well,you are not printing the value of the s1,s2,s3,s4..you are printing the the memory location for s1,s2,s3 and s4 using & operator....

And remember those memory location contains the same instance.....So you are well with your singleton pattern

Upvotes: 2

Related Questions