iOS Swift 3参数在前面有下划线

今天我在Xcode中打开了我的项目,它需要将当前的Swift转换为Swift 3.转换后,我发现函数的所有参数都在前面有一个下划线。 例如, func didGetWeather(_ weather: Weather) {} 。 我试图拿走下划线,它工作正常。 我想知道那些下划线是为了什么。

在swift3之前,默认情况下第一个参数的标签没有在函数调用中列出,在swift3中,没有命名参数的方法是在签名中的参数名称之前放置一个下划线,swift3 migrator添加下划线函数的第一个参数到不要破坏依赖于不在函数调用中放置第一个标签的现有代码。

根据Apple文档:

如果您不想要参数的参数标签,请为该参数写下划线(_)而不是显式参数标签。

func someFunction(_ firstParameterName: Int, secondParameterName: Int) { // In the function body, firstParameterName and secondParameterName // refer to the argument values for the first and second parameters. } // In the function body, firstParameterName and secondParameterName // refer to the argument values for the first and second parameters. }

someFunction(1, secondParameterName: 2)

如果参数具有参数标签,则在调用函数时必须标记参数。

在Swift 2中,我们曾经声明过如下函数:

func myFunc(param1 param:String) {}

我们不得不称之为:

myFunc(param1:)

但后来Apple推出了一种使用下划线(_)省略参数标签的方法,函数声明将是:

func myFunc(_ param:String) {}

然后我们可以通过两种方式调用该函数:

myFunc(_:) // when we don't want to pass any parameters

要么

myFunc(param:"some string") // when we want to pass any parameters

当我们想要定义一个选择器时,第一种方式(使用_)主要用于。 例如:

someButton.addTarget(self, action: #selector(shareCatalog(_:)), for: .touchUpInside)

是的,它在Swift 3.0中的更新日志。

所有函数参数都有标签和“_”,首先是函数:

现在下面所有默认方法也有(_)。

 override func viewWillAppear(_ animated: Bool) override func didMoveToView(_ view: SKView) func textFieldShouldReturn(_ textField: UITextField) -> Bool