例如,我有一个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
这可能吗?
答案 0 :(得分:2)
如果希望返回类型属于您指定的子类,则可以使用泛型:
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
)以访问任何特定于子类的属性。