gpt4 book ai didi

swift - 函数可以返回另一个在 swift 中使用的函数

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

函数是一流的类型。这意味着一个函数可以返回另一个函数作为它的值。

func makeIncrementer() -> (Int -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
var increment = makeIncrementer()
increment(7)

当我执行此操作时出现以下错误:

Command /Applications/Xcode6-Beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift failed with exit code 254

此外,此功能在实时解决方案中的哪些地方有用?

最佳答案

根据 documentation ,你的函数声明应该像下面的代码,请参阅 Int 周围的括号。表示入口参数。

func makeIncrementer() -> (Int) -> Int
^^^^^^^^^^^^

此功能可以使基于运行时值的动态代码变得更加容易。

关于swift - 函数可以返回另一个在 swift 中使用的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24199427/

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