我注意到一些方法,例如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