为对象Swift定义自定义类

时间:2017-06-11 15:36:04

标签: swift macos

例如,我有一个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

一起使用

这可能吗?

1 个答案:

答案 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)以访问任何特定于子类的属性。