gpt4 book ai didi

ios - swift 中的动态类加载

转载 作者:行者123 更新时间:2023-11-30 14:10:52 25 4
gpt4 key购买 nike

我不确定这是否可能,但我的要求是从“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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com