代码如下:
var c = 1
class Singleton {
class var shared: Singleton {
//--struct里边的constant不会被重复定义? why?
struct Static {
static let b = c++
static let instance = Singleton()
}
println("b is \(Static.b)")
return Static.instance
}
}
var single1 = Singleton.shared
c++ ;
var single2 = Singleton.shared
输出结果为:
b is 1
b is 1
问题
为什么b没有改变?
static关键字的含义就是不属于任何类的实例,而是属于类本身,更重要的是,static修饰的对象和变量会在类第一次被加载时存储在内存中的静态储存区域,只要程序在运行,这块区域就不会被清除掉,也就是说static修饰的instance会一直保存在静态储存区域并且只有一份。所以我们在其他类访问instance的时候,都是访问的这块区域,这就是单例模式的原理所在。
thx @dasblinkenlight http://stackoverflow.com/questions/25699945/struct-defined-in-a-function
我想我找到答案了, staic的变量无论怎样都只会被初始化一次:
var g = 0
func f() {
struct InnerStruct{
static var attrStatic:Int = g
var attr = g
}
println("static attr value is \(InnerStruct.attrStatic), g is \(g)")
var inner = InnerStruct()
println(inner.attr)
}
f()
g++
f()
g++
f()
result:
static attr value is 0, g is 0
0
static attr value is 0, g is 1
1
static attr value is 0, g is 2
2
Program ended with exit code: 0