gpt4 book ai didi

function - 如何通过引用传递函数

转载 作者:可可西里 更新时间:2023-11-01 01:42:17 25 4
gpt4 key购买 nike

我正在尝试解决此练习:

Create a function that takes an array of integers, a function passed by reference which will perform an operation on the array and return an Int result.

我有问题。在多次搜索无果后,我将问题分解为代码片段以单独测试每一部分。

我简单的“通过引用代码传递函数”是:

func counter(start:Int)->String{
for var i = 0 ; i<start; ++i{
println("I => \(i)")
}
return "Done"
}

func test(i:Int, inout f:(Int)->String){
f(i)
}

test(5,&counter)

问题是,即使我通过引用传递函数的简单测试也失败了:

(Int)->String is not convertible to @lvalue inout $T3

如果我这样做:

func counter(end:Int)->String{
for var i = 0 ; i<end; ++i{
println("I => \(i)")
}
return "Done"
}

func test(i:Int, inout f:(Int)->String){
f(i)
}

var f1 = counter
test(5,&f1)//pass a reference as an argument to the function

这是通过引用传递吗?由于这有效,我不确定这是正确的。

我做错了什么?

最佳答案

首先,按引用传递 (inout) 适用于以下情况,例如您需要在被调用函数内分配参数并将其分配给调用范围内传递的变量,或者您需要在其中调用 mutating 方法并将其反射(reflect)在调用范围等中。

您没有在 test 中分配给 f。因此,让它成为 inout 是没有意义的,因为它限制了可以传递给它的内容。

从技术上回答你为什么会出错,答案是你不能通过引用传递一个常量变量(即 let),而 counter 是一个常量变量(你不能分配给 counter)。您可以将用于在顶层定义函数的 func 语法视为类似于带有闭包表达式的 let:

func counter(start:Int)->String{ ... }

就像

let counter : Int->String = { (start:Int)->String in ... }

关于function - 如何通过引用传递函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28645729/

25 4 0
文章推荐: javascript - CKEditor 中断
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com