import Foundation public class SwiftSingleton{ var name = "000" public static let instance = SwiftSingleton() //这个位置使用 static,static修饰的变量会懒加载 private init(){ print( "create SwiftSingleton..." ); } } |
然后看测试:
1
2
3
4
5
6
7
8
9
10
11
12
|
override func viewDidLoad() { super.viewDidLoad() print( "viewDidload" ); let s1 = SwiftSingleton.instance let s2 = SwiftSingleton.instance s1.name = "s1" s2.name = "s2" print( "s1.name:(s1.name) s2.name:(s2.name)" ) } |
打印结果:
viewDidload
create SwiftSingleton...
s1.name:s2 s2.name:s2
从打印结果来看,这个单例确实是懒加载的,而且,确实是单例。
OK了