问题答案
代码如下:
 
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没有改变?
标签: swift
答案
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
举一反三