gpt4 book ai didi

swift - swift 中的嵌套函数错误

转载 作者:搜寻专家 更新时间:2023-11-01 06:43:59 26 4
gpt4 key购买 nike

我正在尝试在我的 Swift 程序中使用嵌套函数。

func test()->Bool{
func test1()->Bool{
return true
}

func test2()->Bool{
return true
}

func test3()->Bool{
return true
}
return test1 && test2 && test3
}

它给我一些错误!但是如果我尝试

return test1

它工作正常。

请解释为什么在嵌套函数中应用运算符时出现错误。

最佳答案

嵌套函数/闭包有两种方法:

如你所见:

func test() -> Bool {
func test1() -> Bool {
return true
}

func test2() -> Bool {
return true
}

func test3() -> Bool {
return true
}
return test1() && test2() && test3()
}

或者将其保存到闭包中并调用它们:

func test() -> Bool {
let test1 = { () -> Bool in
return true
}

let test2 = { () -> Bool in
return true
}

let test3 = { () -> Bool in
return true
}

return test1() && test2() && test3()
}

差异非常小,这取决于您自己的喜好,但直接来自文档:

Nested functions are closures that have a name and can capture values from their enclosing function.

Closure expressions are unnamed closures written in a lightweight syntax that can capture values from their surrounding context.

无论哪种方式,这两种情况都必须在名称末尾使用 () 来调用以执行它们的操作,否则您将返回一个函数而不是它的评估。您的 return test1 仅在这种情况下有效:

func test() -> (() -> Bool) {
func test1() -> Bool {
return true
}

return test1
}

您的函数的返回类型是一个函数,在您对其求值后 返回 bool 值。您想要评估并返回与逻辑 AND 语句组合的 Bool 值。因此,您必须评估每个函数以获得每个函数的 Bool 值以将其组合并返回最终值。

关于swift - swift 中的嵌套函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32474871/

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