我早些时候曾问过这个问题,所以你可以了解一些历史,这是 Airspeed Velocity 的一次很棒的尝试,但我觉得我还没有完全做到这一点,所以我将我的问题缩小到非常微小的范围细节才能真正破解。
快速程序接口
您可能会抱怨或否决该问题不完整,但事情就是这样,它基于设计模式,因此如果您不熟悉设计模式或哲学“编程是为了接口而不是为了实现”那么就不要抱怨或投反对票。
寻找能够解决这个问题的 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 failure 11
for animal in animals {
let instance = animal()
instance.speak()
}
您可以使用通用函数来实现这一点:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)