Fervus Fervus - 6 months ago 17
Swift Question

Swift cast AnyObject to protocol and assign property

I am trying to solve a dependency in Swift using an external injector like this:

class DependencyInjector {
var networkManager:NetworkQueueManager

protocol InjectorDelegateNetworkQueue{
var networkManager:NetworkQueueManager {get set}
}

func injectDependencies(object:AnyObject){
if object is InjectorDelegateNetworkQueue{
object.networkManager = networkManager
}
}
}


Obviously, this won't work since
AnyObject
does not have a property called
networkManager
, only the cast object has one.
I mean to call this method inside the init method of other classes, by calling

DependencyInjector.sharedInstance().injectDependencies(self)


How can I get this to work in Swift?

Answer

can maybe go like:

func injectDependencies(object:AnyObject){
        var thing:InjectorDelegateNetworkQueue? = object as? InjectorDelegateNetworkQueue
        if thing {
            thing.networkManager = networkManager
        }
}