理解 Swift 中的命名函数调用与位置函数调用

问题描述 投票:0回答:2

我的代码遇到问题,我试图理解为什么对

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 function arguments
2个回答
0
投票

这是如何运作的?

print(wrapper(function: add))  // Outputs: 3

事实1

wrapper
是一个接收 1 个以下类型参数的函数:

(Int, Int) -> Int

事实2

您的

add
函数的类型是

(Int, Int) -> Int

您可以使用 Xcode 确认这一点:

  1. 将您的函数分配给常量
  2. ctrl + 单击常量名称

结论

由于

wrapper
的参数类型与
add
相同,因此这段代码可以编译

wrapper(function: add)

0
投票

我会尝试简短而简单地解释。

在 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。高阶函数不关心解析函数的外部名称。因为你不会在里面使用任何这些名称。

© www.soinside.com 2019 - 2024. All rights reserved.