class Foo {
var name: String? // instance property
static var all = [Foo]() // static type property
class var comp: Int { // computed type property
return 42
}
class func alert() { // type method
print("There are \(all.count) foos")
}
}
Foo.alert() // There are 0 foos
let f = Foo()
Foo.all.append(f)
Foo.alert() // There are 1 foos
Swift 1.1 doesn't have stored class properties. You can implement it using a closure class property that fetches an associated object tied to the class object. (Only works in classes derived from NSObject.)
private var fooPropertyKey: Int = 0 // value is unimportant; we use var's address
class YourClass: SomeSubclassOfNSObject {
class var foo: FooType? { // Swift 1.1 doesn't have stored class properties; change when supported
get {
return objc_getAssociatedObject(self, &fooPropertyKey) as FooType?
}
set {
objc_setAssociatedObject(self, &fooPropertyKey, newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
}
}
....
}