gpt4 book ai didi

swift - 你如何在 Swift 中做 Java 等效的通用回调接口(interface)

转载 作者:搜寻专家 更新时间:2023-10-31 22:32:24 24 4
gpt4 key购买 nike

在java中你可以这样声明一个接口(interface)

public interface Foo<T>
{
public void doFoo(T result);
}

你可以像这样在另一个方法中使用它作为类型参数

public void doSomeAsyncTask(final Foo<MyObject> foo)
{
Runnable asyncRunnable = new Runnable()
{
@Override
void run()
{
MyObject result;
// do task to get result
foo.doFoo(result);
}
};
Thread asyncThread = new Thread(asyncRunnable);
asyncThread.start();
}

foo.doFoo(result);
}

如您所见,我使用了从在不同线程上运行的一些异步任务回调的接口(interface)。

更新

正在关注 this guide ,我想出了一个类似的解决方案

public protocol GenericProtocol {
associatedType T
func magic(result:T)
}

class GenericProtocolThunk<T> : GenericProtocol {
private let _magic : (T)

init<P : GenericProtocol where P.T == T>(_dep : P) {
_magic = p.magic
}

func magic(result: T) {
_magic(result)
}
}

现在在我的 doSomeAsyncTask方法我可以通过 GenericProtocolThunk<MyObject>作为参数类型。这是实现我在问题中提出的要求的正确方法吗?老实说,我觉得它很丑。

最佳答案

我认为您的问题确实归结为您链接到的博客文章中也指出的内容:

"Protocols in Swift can be generic via abstract type members rather than parameterisation. Consequently, the protocol itself can no longer be used as a type but only as a generic constraint."

基于(丑陋的)thunk 的解决方法看起来确实解决了您的问题,尽管如果在您的问题中您对 Java 和 Swift 示例使用了类似的术语,那么验证它会有所帮助,并且它们将是完整的,包括类型实际上包含 doSomeAsyncTask 方法以避免可能的混淆。

如果您可以稍微更改一下公式,我可以想出一些对 Swift 更友好的替代解决方案。

如果您也可以使用协议(protocol)来描述 Result,那么该语言就不会与您对抗太多。与 Java 相比,遵守协议(protocol)(= 实现接口(interface))也不仅限于类类型,如下面的示例所示,因此可以说,与 Java 相比,您从语言中得到的更多一点:

import Foundation

protocol Result {
// any restrictions on Result that you need.
}

class A:Result { }
struct B:Result { }
enum C:Result { case X }

protocol Foo {
func doFoo(result:Result) -> Void
}

class Bar {
func doSomeAsyncTask(foo:Foo) -> Void {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
foo.doFoo(A())
foo.doFoo(B())
foo.doFoo(C.X)
}
}
}

我自己最近才在相关问题中使用的另一种方法是将结果建模为一个枚举,它枚举了可能的结果类型,如下所示(顺便说一下,每个 BibliographyItemInlineMathFragmentEquationBlockElementInlineElement 在我下面的代码示例本身就是协议(protocol),而不是具体类型):

public enum Result {
case None
case BibliographyItems([BibliographyItem])
case InlineMathFragments([InlineMathFragment])
case Equations([Equation])
case BlockElements([BlockElement])
case InlineElements([InlineElement])
}

如果您的结果来自一些已知的结果类型集,并且您通常最终需要以某种条件形式处理它们,这会很方便。

关于swift - 你如何在 Swift 中做 Java 等效的通用回调接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36937449/

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