Fervus Fervus - 2 years ago 116
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
does not have a property called
, only the cast object has one.
I mean to call this method inside the init method of other classes, by calling


How can I get this to work in Swift?

Answer Source

can maybe go like:

func injectDependencies(object:AnyObject){
        var thing:InjectorDelegateNetworkQueue? = object as? InjectorDelegateNetworkQueue
        if thing {
            thing.networkManager = networkManager
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download