何时从Swift中的另一个函数返回一个函数

时间:2022-03-14 06:26:05

What it the most common situation where you would want to return a function from a function in Swift?

你想要从Swift中的函数返回函数的最常见情况是什么?

In the code below I'm returning a function but I don't really see the purpose since the function I'm returning is inside the function who is returning it. The reason I'm confused is because we could accomplish the same thing with just one function.

在下面的代码中,我正在返回一个函数但我没有真正看到目的,因为我返回的函数是在返回它的函数内部。我感到困惑的原因是因为我们只用一个函数就能完成同样的事情。

func person () -> ((String, Int) -> String) {

  func info(name: String, age: Int) -> (String) {
    return "\(name) is \(age) old"
  }

  return info
}


let nathan = person()
nathan("Nathan", 3)

print(nathan("Nathan", 3))

Can someone point out common situations where you would want to return a function and probably illustrate it with a better example?

有人可以指出你想要返回一个函数的常见情况,并可能用一个更好的例子来说明它吗?

I want to understand this since this is fundamental for programming in general not just Swift (I think).

我想理解这一点,因为这对于编程而言通常不仅仅是Swift(我认为)。

1 个解决方案

#1


7  

A classic example would be in a calculator program, e.g.:

一个典型的例子是计算器程序,例如:

func operatorForString(str: String) -> ((Float, Float) -> Float)? {
    if str == "+" {
        return (+) // brackets required to clarify that we mean the function
    } else if str == "-" {
        return (-)
    } else if str == "*" {
        return (*)
    } else if str == "/" {
        return (/)
    } else if str == "**" {
        return pow // No brackets required here
    } else {
        return nil
    }
}

if let op = operatorForString("-") {
    let result = op(1, 2) // -1
}

It's rather contrived, but it illustrates the principle simply...

这是相当做作的,但它简单地说明了原则......

As an "exercise to the reader" try to do it as a Dictionary lookup, rather than repeated ifs :)

作为“读者的练习”尝试将其作为字典查找,而不是重复ifs :)

#1


7  

A classic example would be in a calculator program, e.g.:

一个典型的例子是计算器程序,例如:

func operatorForString(str: String) -> ((Float, Float) -> Float)? {
    if str == "+" {
        return (+) // brackets required to clarify that we mean the function
    } else if str == "-" {
        return (-)
    } else if str == "*" {
        return (*)
    } else if str == "/" {
        return (/)
    } else if str == "**" {
        return pow // No brackets required here
    } else {
        return nil
    }
}

if let op = operatorForString("-") {
    let result = op(1, 2) // -1
}

It's rather contrived, but it illustrates the principle simply...

这是相当做作的,但它简单地说明了原则......

As an "exercise to the reader" try to do it as a Dictionary lookup, rather than repeated ifs :)

作为“读者的练习”尝试将其作为字典查找,而不是重复ifs :)