【问题标题】:Use `self` as a default parameter使用 `self` 作为默认参数
【发布时间】: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


【解决方案1】:

我可以在 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 这样的东西。稍后会有一个self,当这个方法被调用时,在函数的body里面——因为这个函数会在某个实例上被调用,即self .

一个简单的方法来做你想做的事情是使这个参数成为一个可选的nil默认值。然后,在函数体中,检查nil 并使用self:

class TreeNode {
    func printTree(tree:TreeNode? = nil) {
        let treeToPrint = tree ?? self
        // do stuff
    }
}

现在调用printTree 不带参数是合法的,它会做你想做的事:

TreeNode().printTree()

【讨论】:

  • 哦哦。因为它是在 define 时间解析的......我想知道在这种情况下我是否可以使用惰性评估/自动关闭?让我试试……
【解决方案2】:

之所以unresolved identifier 'self' 是一个实例的隐式属性self' 的范围是在每个实例方法中。如果您在示例中将默认值从 self 更改为 children,您将看到错误

“PeanutButterJelly.Type”没有名为“children”的成员

与 objc 不同,还有另一个版本的 self 引用类的类型,没有这样的东西是 swift

【讨论】:

    猜你喜欢
    • 2019-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    相关资源
    最近更新 更多