【发布时间】:2015-06-12 08:34:59
【问题描述】:
我可以在 Swift 中使用self 作为默认参数吗?这段代码感觉很直接,但我不明白编译器正在回击的消息:
func printTree(node: TreeNode = self, tabs: String = "") {
println(tabs + node.name!)
node.children.forEach { printTree(node: $0, tabs: tabs+"\t") }
}
错误:
'TreeNode -> () -> TreeNode' is not convertible to 'TreeNode'
嗯?
可能还有其他方法可以解决树遍历,但我实际上只是对默认参数限制感到好奇。这是真的吗?文档中是否提到了这一点?我找不到。
更新:
我从头开始做这件事,没有依赖(我之前有一个类层次结构和一个自定义的 forEach 猴子补丁)。它仍然错误:
class PeanutButterJelly {
var children: [PeanutButterJelly]?
func doDance(){ println("dancing") }
func everybodyDanceNow(pbj: PeanutButterJelly = self) {
pbj.doDance()
if let children = pbj.children {
for child in children { child.doDance() }
}
}
}
错误:
Swift compilation error: unresolved identifier 'self'
Xcode 6.3.2
【问题讨论】:
-
例如:避免问题的解决方案:
func printTree(tabs: String = "") { println(tabs + "\(name)") children?.forEach { $0.printTree(tabs: tabs + "\t") } } -
错误必须与您的实现有关,使用
self作为默认参数满足编译器。
标签: swift parameters