gpt4 book ai didi

swift - 我无法弄清楚这个 switch 语句是如何工作的?

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

func performMathAverage (mathFunc: String) -> ([Int]) -> Double {
switch mathFunc {
case "mean":
return mean

case "median":
return median

default:
return mode
}
}

我从一本快速学习书中得到了这个例子,它谈到了返回函数类型的主题,这只是整个程序的一部分,我不想全部复制和粘贴。我的困惑是这本书说:

"Notice in performMathAverage , inside the switch cases, we return either mean , median , or mode , and not mean() , median() , or mode() . This is because we are not calling the methods, rather we are returning a reference to it, much like function pointers in C. When the function is actually called to get a value you add the parentheses suffixed to the function name. Notice, too, that any of the average functions could be called independently without the use of the performMathAverage function. This is because mean , median , and mode are called global functions ."

主要问题是:“为什么我们不调用方法?”我们返回对它的引用是什么意思??

引用是什么意思?我只是对这部分感到困惑。

最佳答案

您将您的主要问题表述为:

“为什么我们不调用方法?”我们返回对它的引用是什么意思??

一开始理解起来有点棘手,但它的意思是我们不想要函数的结果,我们想要函数本身。

有时像这样的事情使用类型别名更容易理解:

[Int] -> Int 开始,我们所说的是“一个接受 Int 数组并返回单个 整数"

为了清楚起见,让我们创建一个类型别名:

typealias AverageFunction = [Int] -> Int

现在我们的函数(来自您的示例)如下所示:

func performMathAverage(mathFunc: String) -> AverageFunction {

不过,这里的命名约定很困惑,因为我们没有执行任何操作,而是让我们这样调用它:

func getAverageFunctionWithIdentifier(identifier: String) -> AverageFunction {

现在很明显,这个方法的功能就像一个工厂,它根据我们提供的标识符向我们返回一个平均函数。现在让我们看看实现:

func getAverageFunctionWithIdentifier(identifier: String) -> AverageFunction {
switch identifier {
case "mean":
return mean
case "median":
return median
default:
return mode
}
}

现在,我们在标识符上运行一个开关以找到相应的函数。同样,我们不调用该函数是因为我们不想要该值,我们想要该函数本身。让我们看看如何调用它:

let averageFunction = getAverageFunctionWithIdentifier("mean")

现在,averageFunction 是对 mean 函数的引用,这意味着我们可以使用它来获取整数数组的平均值:

let mean = averageFunction([1,2,3,4,5])

但是如果我们想使用不同类型的平均数,比如中位数呢?除了标识符,我们不必更改任何内容:

let averageFunction = getAverageFunctionWithIdentifier("median")
let median = averageFunction([1,2,3,4,5])

这个例子非常人为,但这样做的好处是通过将函数抽象为它的类型(在本例中 [Int] -> Int,我们可以使用任何符合该类型可互换。

这就是函数式编程!

关于swift - 我无法弄清楚这个 switch 语句是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31991812/

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