在运行时动态地从protocol.Type引用实例化

时间:2014-12-17 21:02:40

标签: swift introspection

我之前已经问过这个问题,所以你可以了解一些历史,这是Airspeed Velocity的绝佳尝试,但我觉得我还没到那里,所以我&#39 ;我将我的问题缩小到非常微小的细节,以便真正破解它。

swift program to interface

你可以投诉或拒绝投票,问题是不完整的但是它是如何发展的,它是基于设计模式的,所以如果你不熟悉设计模式或哲学 "计划不与实施接口" 然后不投诉或投票。

寻找可以破解它的SWIFT大师。

一切顺利。

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)

     }
}

修改 真棒马丁 ......你破解了它。 抱歉,我错过了这部分,

假设您是所有这些实现类的数组,那么您如何迭代实例化并调用speak(请记住实现类Cat在这种情况下对于测试是不知道的)

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

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

//我在游乐场尝试导致它出现一些问题,编译器抛出错误Segmentation fault11

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

1 个答案:

答案 0 :(得分:4)

您可以使用通用功能实现此目的:

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

示例:

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

// ...

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