我需要维护类类型的对象/实例的数量,分别处理Base及其子类。
我有Base类和 n Base类的子类
我正在尝试将静态var计数器实现为我的基类中的字典。
我正在尝试实现基类,就像这样,我敲响了声明struct static dictionary getter&的类变量。设定器
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"
}
}
看来上面的工作正如预期的那样!!
我在项目中实施并测试后会更新。
答案 0 :(得分:0)
我在项目中实现的最终工作版本如下,
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"
}
func getType() -> String {
return "Base"
}
init() {
switch self.getType() {
case BaseClass.getType():
BaseClass.typeCounter = 1
case SubClass.getType():
SubClass.typeCounter = 1
default: break
}
}
deinit {
switch self.getType() {
case BaseClass.getType():
BaseClass.typeCounter = -1
case SubClass.getType():
SubClass.typeCounter = -1
default: break
}
}
}
class SubClass:BaseClass {
override class func getType() -> String {
return "SubClass"
}
override func getType() -> String {
return "SubClass"
}
}
如果有人有更好的解决方案,请告诉我们,谢谢