gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 20:22:04 25 4
gpt4 key购买 nike

我有一个硬编码的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/

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