Create an instance from the protocol. Type a link dynamically at runtime

I asked this question before so you can get a little history. It was a terrific attempt at Airspeed Velocity, but I feel like I haven't gotten there yet, so I'm narrowing my question down to the smallest detail to really break it down.

fast interface program

You can complain or lower your voice, this question is incomplete, but as it happens, it is based on design patterns, so if you are not familiar with design patterns or the philosophy of "Program to interact with not implementation" then do not complain or vote ...

Looking for a SWIFT guru who can crack it.

All the best.

public protocol IAnimal {
    init()
    func speak()
}

class Test {
     func instantiateAndCallSpeak(animal:IAnimal.Type) {
         //use the animal variable to instantiate and call speak - 
         //no implementation classes are known to this method
         //simply instantiate from the IAnimal reference at run time.
         //assume the object coming in via does implement the protocol (compiler checks that)

     }
}

      

Edit Awesome Martin ... you hacked it. sorry i missed this part,

suppose if you have an array of all these implementation classes, how are you iterating over the instance and talking on the phone (remember that the Cat implementation class in this case is not familiar with the test)

var animals:[IAnimal.Type] = [Cat.self, Dog.self, Cow.self] 

//and so many more implementation classes not known to test method

      

// my attempt at playground caused some problems with it, the compiler threw an error. Segmentation fault11

for animal in animals {
    let instance = animal()
    instance.speak()
}

      

+3


source to share


1 answer


You can achieve this with a generic function:

class Test {
    func instantiateAndCallSpeak<T: IAnimal>(animal:T.Type) {
        let theAnimal = animal()
        theAnimal.speak()
    }
}

      



Example:

class Cat : IAnimal {
    required init() {
    }
    func speak() {
        println("Miau"); // This is a german cat
    }
}

// ...

let t = Test()
t.instantiateAndCallSpeak(Cat.self) // --> Miau

      

+4


source







All Articles