Swift 单例

1.

代码:

import UIKit

class Test: NSObject {
    private static let _shared = Test()
    class func shared() -> Test {
        return _shared;
    }
    private override init() {
        super.init()
    }
    
    var str: String? = nil;
}

调用:

Test.shared().str = "Hello World";

print(Test.shared().str!)

2.

代码:

import UIKit

class Test: NSObject {
    static let shared = Test()
    private override init() {
        super.init()
    }
    
    var str: String? = nil;
}

调用:

Test.shared.str = "Hello World";

print(Test.shared.str!)

销毁单例

一般来说单例是没有必要这么做,假如要真的要这么做的话,请看下面:

1.

这个方法显然不太适合写销毁单例。

2.

代码:

import UIKit

class Test: NSObject {
    static var shared: Test? = Test()
    
    private override init() {
        super.init()
    }
    
    class func destroy() {
        shared = nil;
    }
    
    var str: String? = nil;
}

调用:

Test.shared?.str = "Hello World";
        
Test.destroy()
        
if let str = Test.shared?.str! {
    print(str)
} else {
    print("没有内容")
}