【发布时间】:2015-02-19 14:42:49
【问题描述】:
我需要维护类类型的对象/实例的数量,分别处理 Base 及其子类。
我有 Base 类和 Base 类的 n 个子类
我正在尝试在我的基类中实现一个静态变量计数器作为字典。
我正在尝试实现基类,就像这样,我在声明 struct static dictionary getter & setter 的类变量时大吃一惊
class BaseClass {
struct objCounter {
static var counter = [String:Int]()
subscript(type: String) -> Int? {
get { return objCounter.counter[type] }
set(value) { objCounter.counter[type] = value }
}
}
class var typecounter: [String:Int] {
?? //
}
}
或者有没有更好的方法来做到这一点
更新 我正在尝试这样的东西,它适用于基类,现在我正在尝试修改它以适用于子类,有什么想法吗?
class var typecounter:Int? {
get {
return objCounter.counter["base"]
}
set {
if let value = objCounter.counter["base"] {
objCounter.counter["base"] = value + newValue!
} else {
objCounter.counter["base"] = newValue
}
}
}
我正在尝试实现的最终版本是
class BaseClass {
struct objCounter {
static var counter:[String:Int] = [String:Int]()
subscript(type: String) -> Int? {
get {
return objCounter.counter[type]
}
set(value) {
objCounter.counter[type] = value
}
}
}
class var typecounter:Int? {
get {
return objCounter.counter[self.getType()]
}
set {
if let value = objCounter.counter[self.getType()] {
objCounter.counter[self.getType()] = value + newValue!
} else {
objCounter.counter[self.getType()] = newValue
}
}
}
class func getType() -> String {
return "Base"
}
}
class SubClass:BaseClass {
override class func getType() -> String {
return "SubClass"
}
}
看来上面的工作正常!!
一旦我在我的项目中实施并测试了它,我会更新。
【问题讨论】: