在运行时从protocol.Type引用动态实例化 [英] instantiate from protocol.Type reference dynamically at runtime

查看:67
本文介绍了在运行时从protocol.Type引用动态实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我早些时候曾问过这个问题,以便您了解一些历史,那是Airspeed Velocity的一次了不起的尝试,但我觉得我还没有到达那里,所以我缩小了我的问题范围细化细节,以便对其进行真正的打击.

I've asked this question earlier at so you get to know a bit of history, It was an awesome attempt by Airspeed Velocity there but I feel I didn't quite get there yet, so I'm narrowing down my question to very minute details in order to really crack it down.

将程序连接到界面

您可能会抱怨或否定该问题不完整,但这是如何解决的,它是基于设计模式的,因此,如果您不熟悉设计模式或理念,那么程序不与实现接口对接" /strong>,请不要抱怨或投反对票.

You may complain or down vote that question is incomplete but that's how it goes, It's based on design patterns, so if you're not familiar with design patterns or philosophy "Program to interface not to an implementation" then don't complaint or down vote.

寻找SWIFT专家谁可以对其进行严厉打击.

Looking out for SWIFT guru's who can crack it down.

祝一切顺利.

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 cracked it. sorry I missed this part,

假设您拥有所有这些实现类的数组,那么如何迭代实例化并调用语音(请记住测试中未知这种情况下的实现类Cat)

suppose if you've an array of all those implementation classes, how'd you iterate instantiate and call speak (remember implementation class Cat in this case is not known to the test)

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

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

///我在操场上的尝试引起了一些问题,编译器抛出了错误Segmentation fault11

//my attempt in playground causing some issues with it, compiler thrown an error Segmentation fault11

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

推荐答案

您可以使用通用函数来实现:

You can achieve that with a generic function:

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

这篇关于在运行时从protocol.Type引用动态实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆