例如,我有一个BaseObject
类:
class BaseObject: NSObject {
let id:UInt64
}
和此对象的管理器类:
public class Manager: NSObject {
public var objs:[BaseObject] = []
public func addObj(obj:BaseObject) {
...
}
}
我想创建一个库,并允许开发人员设置自己的类,该类应该继承自
Base Object
例如:
class MyOwnBaseObject: BaseObject {
var ownProperty:Int = 0
}
var manager = Manager();
manager.objClass = MyOwnBaseObject
manager.objs
现在应该返回:[MyOwnBaseObject]
并且manager.addObj()
应该与MyOwnBaseObject
一起工作这可能吗?
最佳答案
如果希望返回类型属于指定的子类,可以使用泛型:
public class BaseObject: NSObject {
let id:UInt64 = 0
}
public class MyOwnBaseObject: BaseObject {
var ownProperty:Int = 0
}
public class Manager<T>: NSObject {
public var objs:[T] = []
public func addObj(obj:T) {
objs.append(obj)
}
}
var manager = Manager<BaseObject>()
let ob1 = BaseObject()
manager.addObj(obj: ob1)
let ob2 = BaseObject()
manager.addObj(obj: ob2)
var otherManager = Manager<MyOwnBaseObject>()
let ownOb1 = MyOwnBaseObject()
otherManager.addObj(obj: ownOb1)
let ownOb2 = MyOwnBaseObject()
otherManager.addObj(obj: ownOb2)
print(manager.objs) // objs is of type [BaseObject]
print(otherManager.objs) // objs is of type [MyOwnBaseObject]
如果没有泛型,代码仍然可以工作,但是需要将
objs
返回的任何对象强制转换到自定义类(例如MyOwnBaseObject
)以访问任何子类特定的属性。