ios swift方法参数

时间:2016-06-18 12:12:21

标签: ios swift

我正在阅读快速入门苹果指南。他们提供以下代码:

required init?(coder aDecoder: NSCoder) 

为什么他们两个参数名称?编码器和解码器。

我不明白为什么我们不使用这种有效的语法:

required init?(coder: NSCoder) 

谢谢。

1 个答案:

答案 0 :(得分:2)

coder是外部参数名称。它在调用方法时使用:

SomeClass(coder: someCoder)

aDecoder是本地参数名称。它在方法内部使用:

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

您可以只指定本地参数名称:

required init?(coder: NSCoder)

在这种情况下,外部参数名称会自动采用相同的值coder。 主要用途是可读性。你的例子不是很明显。让我们从 Eric D

发布的link中获得更好的结果
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"))

但在这种情况下,局部变量使用错误的命名风格