function - 为什么编译器以不同的方式对待闭包和局部函数?

标签 function swift closures

我认为闭包和函数是一回事。但是当在本地函数编译器中引用属性时不需要 self.但是在闭包里面需要写 self.我的意思是为什么这两件事不同?

为清楚起见,示例代码:

class Foo {
    let bar = "bar"

    func baz() {
        func localBaz() {
            println(bar)   // No complain from compiler.
        }

        let bazClosure = {
            println(self.bar) // Here if I write just println(bar), compiler complains.
        }
    }
}

最佳答案

你的期望是错误的 - Swift 中的函数和闭包不是一回事。 func 本质上是用 [unowned self] 声明设置一个 lazy var 绑定(bind)。因此,如果您想摆脱 func,您可以转换以下内容:

class Foo {
  let bar = "bar"
  // this is not your 'baz'; just an example
  func baz () { println (bar) }
  }
}

作为

class Foo {
  let bar = "bar"
  lazy var baz = { [unowned self] in println (self.bar) }
}

你可以看到 func 不仅仅是一个闭包。

此外,重要的是,func 设置了一个递归绑定(bind)环境,允许 func bar 的主体引用 bar。因此你可以这样写:

  1> class Foo { 
  2.     func fact (x:Int) -> Int {
  3.         if 1 == x { return x } 
  4.         else { return x * fact (x - 1) }} 
  5. }    
  6> Foo().fact(5)
$R0: (Int) = 120

但不是

  7> class Foo { 
  8.     lazy var fact = { (x:Int) -> Int in 
  9.         if 1 == x { return x } 
 10.         else { return x * fact (x - 1) }}} 
repl.swift:10:27: error: variable used within its own initial value
        else { return x * fact (x - 1) }}}

                      ^

关于function - 为什么编译器以不同的方式对待闭包和局部函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27476426/

相关文章:

function - 函数的强制参数和默认参数

用于将鼠标悬停在一张图片上以在固定位置显示另一张带有描述的 Javascript

JavaScript 函数回调

ios - Swift 4 .plist 处理

swift - Swift 中的 block 引用

c - 这个c程序编译运行后出现未知错误

ios - 使用 Sprite Kit 和 Swift 从另一个场景影响 child

ios - 带有 tableFooterView 的空 UITableView

rust - 在 Rust 闭包中重用绑定(bind)

iOS swift 为什么两种类型的闭包不能添加到数组