Swift函数,一个参数有两个名字

标签 swift function parameters

<分区>

我注意到一些方法,例如init(nibName nibName: String?, bundle nibBundle: NSBundle?) 一个参数有两个“名称”,除了第一个不能在方法内部使用。在这种情况下,您无法使用 bundle 但可以使用 nibBundle。例如,当我调用 super.init(nibName: nibName, bundle: bundle) 时,我收到错误“使用未解析的标识符‘bundle’”。

我的问题是:它(双命名参数)有什么用?如何正确使用?

编辑:现在很明显是外部参数名称。 我有 UIViewController 的子类并重写以下方法。我不明白 nibBundle 从哪里来?显然它没有在函数头中定义。

override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
   super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
   let someBundle = nibBundle
   print(someBundle)
}

最佳答案

来自 Apple 的文档:

Sometimes it’s useful to name each parameter when you call a function, to indicate the purpose of each argument you pass to the function.

If you want users of your function to provide parameter names when they call your function, define an external parameter name for each parameter, in addition to the local parameter name. You write an external parameter name before the local parameter name it supports, separated by a space:

func someFunction(externalParameterName localParameterName: Int) {
    // function body goes here, and can use localParameterName
    // to refer to the argument value for that parameter
}

简写外部参数名称

If you want to provide an external parameter name for a function parameter, and the local parameter name is already an appropriate name to use, you do not need to write the same name twice for that parameter. Instead, write the name once, and prefix the name with a hash symbol (#). This tells Swift to use that name as both the local parameter name and the external parameter name.

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html

关于Swift函数,一个参数有两个名字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32039579/

相关文章:

ios - 如何在 UIWebView swift 中自动播放 YouTube 视频

python - Swift 序列化使用 Python 生成的稀疏矩阵

function - 在语言层面, `ccall` 到底是什么?

java - 在 JSP 中将 Javascript 值传递给 Java

ios - 向下/向上滚动时 TableView 出现不一致的行为

ios - Tableview 中的 Swift Firebase Firestore 数据

c - C 中的通用列表操作函数?

javascript - 稍后在不使用 .prototype 的情况下将其他功能添加到类中

vb.net - 如何从vb.net中的文本框传递 Crystal 报表中文本字段中的值

nhibernate - 如何在名为IQuery参数的NHibernate上设置C#可为空的值键入值?