使用`self`作为默认参数

时间:2015-06-12 08:35:00

标签: swift parameters

我可以在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'

咦?

我可能还有其他方法可以解决树遍历,但我实际上只是对默认参数限制感到好奇。这是真的吗?在文档中是否提到了这一点?我找不到一个。

更新

我是从头开始做的,没有依赖(我之前有一个类heirarchy和一个自定义的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

2 个答案:

答案 0 :(得分:16)

  

我可以在Swift中使用self作为默认参数

没有。这基本上与初始化实例方法时无法说self的原因相同:

class TreeNode {
    var otherNode : TreeNode = self // Use of unresolved identifier `self`
    func printTree(tree:TreeNode = self) { } // Use of unresolved identifier `self`
}

当你定义这个实体(属性或方法)时,没有self这样的东西。稍后,当此方法被称为时,会在函数的 body 中有一个self - 因为该函数将在某个实例上调用,即{ {1}}。

执行您要执行的操作的一种简单方法是使此参数成为可选,并带有self默认值。然后,在函数正文中,检查nil并使用nil

self

现在,在没有参数的情况下调用class TreeNode { func printTree(tree:TreeNode? = nil) { let treeToPrint = tree ?? self // do stuff } } 是合法的,它可以按照您的意愿执行:

printTree

答案 1 :(得分:0)

dplyr是一个实例的隐式属性filter(df, col2 == "Mazda", col1 == "10") '的范围的原因在于每个实例方法。如果您在示例中将默认值从self更改为children,则会看到错误

  

'PeanutButterJelly.Type'没有名为'children'的成员

不像在objc中有另一个版本的self引用类的类型没有这样的东西是swift