我正在阅读快速入门苹果指南。他们提供以下代码:
required init?(coder aDecoder: NSCoder)
为什么他们两个参数名称?编码器和解码器。
我不明白为什么我们不使用这种有效的语法:
required init?(coder: NSCoder)
谢谢。
答案 0 :(得分:2)
coder
是外部参数名称。它在调用方法时使用:
SomeClass(coder: someCoder)
aDecoder
是本地参数名称。它在方法内部使用:
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
您可以只指定本地参数名称:
required init?(coder: NSCoder)
在这种情况下,外部参数名称会自动采用相同的值coder
。
主要用途是可读性。你的例子不是很明显。让我们从 Eric D :
func sayHello(to person: String, and anotherPerson: String) -> String {
return "Hello \(person) and \(anotherPerson)!"
}
print(sayHello(to: "Bill", and: "Ted"))
在调用sayHello
方法时比
func sayHello(person: String, anotherPerson: String) -> String {
return "Hello \(person) and \(anotherPerson)!"
}
print(sayHello(person: "Bill", anotherPerson: "Ted"))
当然你可以写
func sayHello(to: String, and: String) -> String {
return "Hello \(to) and \(and)!"
}
print(sayHello(to: "Bill", and: "Ted"))
但在这种情况下,局部变量使用错误的命名风格