无法在swift中viewDidLoad()
重载功能。
它给出了错误definition conflict with previous value" at "func joinString(#strings: String...) -> String {
override func viewDidLoad() {
super.viewDidLoad()
func joinString(#strings: String[]) -> String {
var str = ""
for s in strings {
str += s
}
return str
}
func joinString(#strings: String...) -> String {
return joinString(strings: strings)
}
println(joinString(strings : ["I", "am", "an", "array"]))
println(joinString(strings : "I", "am", "an", "array"))
}
答案 0 :(得分:3)
对我来说,这看起来像是一个Swift bug(或一个没有文档的限制)。 函数/方法重载通常工作,即使是数组与可变参数:
class MyClass {
func foo(arg: Int) { println("An integer") }
func foo(arg: Double) { println("A double") }
func joinString(#strings: String[]) { println("An array") }
func joinString(#strings: String...) { println("Variadic parameters")}
func test() {
foo(2)
foo(3.14)
joinString(strings : ["I", "am", "an", "array"])
joinString(strings : "I", "am", "an", "array")
}
}
并产生预期的输出:
An integer A double An array Variadic parameters
但是重载不适用于嵌套函数:
class MyClass {
func test() {
func foo(arg: Int) { println("An integer") }
func foo(arg: Double) { println("A double") }
// error: definition conflicts with previous value
func joinString(#strings: String[]) { println("An array") }
func joinString(#strings: String...) { println("Variadic parameters")}
// error: definition conflicts with previous value
func test() {
foo(2)
foo(3.14)
joinString(strings : ["I", "am", "an", "array"])
joinString(strings : "I", "am", "an", "array")
}
}
}
答案 1 :(得分:2)
你不能以这种方式超载:
func joinString(#strings: String[]) -> String {
...
}
func joinString(#strings: String...) -> String {
...
}
joinString函数实际上具有相同的签名。两者都采用Array但可变版本的签名会导致编译器使用调用站点传递的参数生成Array。