ios - swift 中的动态类加载

标签 ios swift

我不确定这是否可能,但我的要求是从“A”类加载颜色,但在内部它将引用/创建 B 或 C 的对象,其中定义了实际方法。取决于某些条件,A 只会为 B 或 C 创建一次引用/对象。如果我调用 A 上的方法,那么我需要从 B 或 C 获取而不再次检查条件。假设 B 和 C 具有相同的方法签名。

这可能吗?如果是这样,我们怎样才能实现这一目标。 PS:使用 swift。

最佳答案

听起来你需要protocol

protocol myCustomProtocol {
    func myCallBackFunction();
}

class A : myCustomProtocol{

    func myCallBackFunction(){
        println("I AM A")
    }
}

class B : myCustomProtocol{

    func myCallBackFunction(){
        println("I AM B")
    }
}

class C{

    func doSomethingWithMyCustomProtocol(mcp : myCustomProtocol){
        mcp.myCallBackFunction();
    }
}

var myA = A();
var myB = B();
var myC = C();

myC.doSomethingWithMyCustomProtocol(myA);
myC.doSomethingWithMyCustomProtocol(myB);

//output: 
//I AM A
//I AM B

关于ios - swift 中的动态类加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31786146/

相关文章:

ios - 如何在 Swift 中记录完整的 POST 请求

iphone - 如何将数据从一个 View 传回 IOS 中的另一个 View ?

swift - 检查 imapsession 的连接是否已建立

ios - UITableView 被释放 IOS SWIFT 随机崩溃

ios - 在 Swift 中使用 commitEditingStyle 动态删除 UITable 部分

iphone - 如何在右耳机上播放音频,在左耳机上播放音乐?

ios - 如何以编程方式将键盘更改为指定语言

ios - 将具有 "\n"的数组元素合并到 Swift 中的字符串中

swift - 将 firebase pod 更新到最新版本时收到 "framework not found MeasurementNanoPB"错误

ios - 线程 1 : signal SIGABRT Login Button Causes App to Crash