例如,我有一个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)以访问任何子类特定的属性。

09-25 18:46