我的代码遇到问题,我试图理解为什么对
add
的初始调用因“缺少参数”错误而失败,而当传递到另一个函数(在没有参数标签。
我在如果 Swift 也需要参数顺序,为什么还需要参数名称?找到了关于此主题的讨论,但我很难掌握所有细节并确定其与我的查询的相关性。
func add(x: Int, y: Int) -> Int {
x + y
}
func wrapper(function: (Int, Int) -> Int) -> Int {
function(1, 2) // Why does this not produce a "Missing argument" error?
}
// "Missing argument" error
// print(add(1, 2))
// No Error - I think I understand why this works
print(add(x: 1, y: 2)) // Outputs: 3
// How does this work?
print(wrapper(function: add)) // Outputs: 3
我会尝试简短而简单地解释。
在 Swift 中,你可以忽略很多你不关心的事情。 (例如值、数字、名称等)
在函数中,每个参数有两个名称(标签):
func example(externalName internalName: MyType) -> ReturnType
您可以使用
_
忽略您不关心的名称,例如:
// Don't care about the external name
func example(_ internalName: MyType) -> ReturnType
// Will be called like
example("Some Value")
// --
// Don't care about the external name
func example(externalName _: MyType) -> ReturnType
// Will be called like
example(externalName: "Some Value")
function
中的wrapper
参数的类型是(Int, Int) -> Int
,这意味着接受两个整数并返回一个Integer。高阶函数不关心解析函数的外部名称。因为你不会在里面使用任何这些名称。