Swift 初始化程序和函数中参数之间的语法差异
Swift syntax discrepancy between parameters in initializer and functions
在我看来,Swift 的语法在调用初始化程序和至少有一个参数的函数之间存在差异。
让我们考虑这两个例子:
class SimpleClass {
var desc: String
init(desc: String) {
self.desc = desc
}
}
let aClass = SimpleClass(desc: "description")
和
func simpleFunc(a: Int, b:Int) -> Int {
return a + b;
}
let aVal = simpleFunc(5, b: 6)
编译器强制你在函数调用中省略第一个标签,这对我来说似乎很奇怪,否则你会得到一个错误 "Extraneous argument label 'a:' in call"。而如果我们想在初始化期间省略第一个标签,则会出现错误 "Missing argument label 'desc:' in call".
语言指南说:
When calling a function with more than one parameter, any argument after the first is labeled according to its corresponding parameter name.
The arguments to the initializer are passed like a function call when
you create an instance of the class.
我是 Swift 的新手,所以我希望我没有遗漏任何东西,但这似乎是语法差异,因为初始化器/构造器只是一种函数,并强制省略第一个标签函数调用对我来说似乎不一致。
那是因为Swift注重可读性;函数调用能够像句子一样被阅读。请参阅 this,特别是关于 "Local and External Parameter Names for Methods" 的部分。为了符合这种风格,您的功能应该更像是:
func add(a: Int, to b: Int) -> Int {
return a + b
}
let c = add(1, to: 2)
在我看来,Swift 的语法在调用初始化程序和至少有一个参数的函数之间存在差异。
让我们考虑这两个例子:
class SimpleClass {
var desc: String
init(desc: String) {
self.desc = desc
}
}
let aClass = SimpleClass(desc: "description")
和
func simpleFunc(a: Int, b:Int) -> Int {
return a + b;
}
let aVal = simpleFunc(5, b: 6)
编译器强制你在函数调用中省略第一个标签,这对我来说似乎很奇怪,否则你会得到一个错误 "Extraneous argument label 'a:' in call"。而如果我们想在初始化期间省略第一个标签,则会出现错误 "Missing argument label 'desc:' in call".
语言指南说:
When calling a function with more than one parameter, any argument after the first is labeled according to its corresponding parameter name.
The arguments to the initializer are passed like a function call when you create an instance of the class.
我是 Swift 的新手,所以我希望我没有遗漏任何东西,但这似乎是语法差异,因为初始化器/构造器只是一种函数,并强制省略第一个标签函数调用对我来说似乎不一致。
那是因为Swift注重可读性;函数调用能够像句子一样被阅读。请参阅 this,特别是关于 "Local and External Parameter Names for Methods" 的部分。为了符合这种风格,您的功能应该更像是:
func add(a: Int, to b: Int) -> Int {
return a + b
}
let c = add(1, to: 2)