java - 如何像 Java 接口(interface)一样在 swift 中使用闭包

标签 java swift interface closures

我有一个硬编码的java代码片段,如下所示。如何使用协议(protocol)或其他 swift 东西在 Swift 3 上重写此代码。

interface Startable {
 int started(String name);
}

class A{
    private String name;
    private Startable startable;

    public A(String name, Startable startable) {
        name = name;
        startable = startable;
    }

    public void doSomething() {
        if (startable != null) {
            startable.started(name);
        }
    }
}

最佳答案

在你的Java示例中Startable是一个“函数接口(interface)”,它在Swift中被称为“函数类型”,我认为这就是你对Closure的意思>,参见 Swift Functions 中的“函数类型”部分.

来自 Swift 文档:

Function Types

Every function has a specific function type, made up of the parameter types and the return type of the function.

For example:

func addTwoInts(_ a: Int, _ b: Int) -> Int {
    return a + b
}
func multiplyTwoInts(_ a: Int, _ b: Int) -> Int {
    return a * b
}

This example defines two simple mathematical functions called addTwoInts and multiplyTwoInts. These functions each take two Int values, and return an Int value, which is the result of performing an appropriate mathematical operation.

The type of both of these functions is (Int, Int) -> Int.

...

Using Function Types

You use function types just like any other types in Swift. For example, you can define a constant or variable to be of a function type and assign an appropriate function to that variable:

var mathFunction: (Int, Int) -> Int = addTwoInts

This can be read as:

“Define a variable called mathFunction, which has a type of "a function" that takes two Int values, and returns an Int value.’ Set this new variable to refer to the function called addTwoInts.”

...

如果您想要执行与 Java 示例中完全相同的操作,那么您可以在 Swift 中编写为

class A {

    var name : String
    var startable : ((String) -> Int)?

    init(_ name : String, _ startable : ((String) -> Int)?) {
        self.name = name
        self.startable = startable
    }

    func doSometing() {
        if let fn = startable {
           fn(name)
        }
    }   
}

关于java - 如何像 Java 接口(interface)一样在 swift 中使用闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44567862/

相关文章:

java - MapBox Android SDK : How to download offline map during app installation?

ios - 将 EnvironmentObject 传递给 ObservableObject 类

ios - 在Xcode11/iOS13或13.1中自定义UITabBar高度

c# - 为 WCF 实现接口(interface)时不能使用可选参数

c# - 我的抽象类实现了一个接口(interface),但没有实现它的一些方法。我如何让它编译?

c++ - 接口(interface)和实现 C++

java - 如何使用 sendirect() 方法将搜索查询从 servlet 传递到 jsp

java - 原始类型和包装类之间的主要区别是什么?

java - 获取一周中特定日期的日期

swift - 在单元格中设置 imageView