简体   繁体   中英

Define custom class for object Swift

For example i have a BaseObject class:

class BaseObject: NSObject {
    let id:UInt64
}

And manager class for this objects:

public class Manager: NSObject {
    public var objs:[BaseObject] = []

    public func addObj(obj:BaseObject) {
        ...
    }
}

I want to create a library, and to allow developer set his own class that should inherit from Base Object

For example:

class MyOwnBaseObject: BaseObject {
   var ownProperty:Int = 0
}

var manager = Manager();
manager.objClass = MyOwnBaseObject

and manager.objs should now return: [MyOwnBaseObject] and manager.addObj() should work with MyOwnBaseObject

Is this possible ?

If you want the return type to be of the subclass you specified, you can use generics:

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]

Without generics, you code would still work, but you would need to cast any of the objects returned by objs to the custom class (such as MyOwnBaseObject ) to access any subclass-specific properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM