gpt4 book ai didi

Swift 中等效的 Java 接口(interface)

转载 作者:搜寻专家 更新时间:2023-11-01 05:56:33 25 4
gpt4 key购买 nike

<分区>

EDIT: What is different between What is the equivalent for java interfaces or objective c protocols in swift? and this question?

阅读该主题后,我认为使用类来扩展协议(protocol)是一种选择,并且我尝试创建协议(protocol)本身但没有成功,但正如 Duncan C. 所说这是不可能的直接初始化一个协议(protocol)类型,我必须用另一个类来扩展它。

我的问题:我有一个 Java 类,我有一个接口(interface)数组,这样我就可以遍历数组并调用 doWork() 函数,直到其中一个返回 true。我想在 Swift 中实现相同的功能。

我的java类:

class MyClass{
//create a variable that holds all of my engines
private MyEngine[] myEngines = new MyEngine[]{
new MyEngine(){
@Override
public boolean doWork(){
return doWork1();
}
},
new MyEngine(){
@Override
public boolean doWork(){
return doWork2();
}
},
new MyEngine(){
@Override
public boolean doWork(){
return doWork3();
}
}
}

//loop through all engines until one of them succeed
public boolean doWorkUntilSuccess(){
for(int i = 0; i < myEngines.length; i++){
if(myEngines[i].doWork())
return true;
}
return false;
}

private boolean doWork1(){
//code
return result;
}

private boolean doWork2(){
//code
return result;
}

private boolean doWork3(){
//code
return result;
}

interface MyEngine{
boolean doWork();
}
}

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