无法对Swift中的闭包做出弱引用

use*_*008 13 closures weak-references objective-c-blocks retain-cycle swift

更新:我尝试编写它而不会使它变弱,并且似乎没有泄漏.所以也许问题不再是必要的.


在Objective-C ARC中,当你想让一个闭包能够在闭包内部使用它时,该块不能捕获对它自身的强引用,或者它将是一个保留循环,所以你可以使闭包捕获一个对自身的弱引用,如下:

// This is a simplified example, but there are real uses of recursive closures
int (^fib)(int);
__block __weak int (^weak_fib)(int);
weak_fib = fib = ^(int n) {
  if (n < 2)
    return n;
  else
    return weak_fib(n-1) + weak_fib(n-2);
};
Run Code Online (Sandbox Code Playgroud)

我试图将其转换为Swift:

var fib: (Int -> Int)?
fib = { [weak fib] (n: Int) in // 'weak' cannot be applied to non-class type 'Int -> Int'
  if n < 2 {
    return n
  } else {
    return fib!(n-1) + fib!(n-2)
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,Swift编译器不允许我声明一个弱被捕获的函数('weak' cannot be applied to non-class type 'Int -> Int').[unowned fib]也不起作用('unowned' cannot be applied to non-class type '(Int -> Int)?').

我知道函数不是Swift中的类类型.但是,它们是参考类型,它们确实参与引用计数.因此,难道不应该有办法让他们弱或无主的参考?

如何在没有保留周期的Swift中编写递归闭包?

jtb*_*des 6

目前看来这是不可能的; 你可能想提交一个bug.

但是你可以使用实际的方法func来实现同样的目的:

func fib(n: Int) -> Int {
    if n < 2 {
        return n
    } else {
        return fib(n-1) + fib(n-2)
    }
}

fib(10) // 55
Run Code Online (Sandbox Code Playgroud)

计算机科学欢乐时光!为了更直接地翻译代码,我们可以 Swift的内置curried函数定义的帮助下使用Z组合器:

func Z<T, U>(f: (T -> U, T) -> U)(x: T) -> U {
    return f(Z(f), x)
}

let fib = Z { (fib: Int -> Int, n: Int) in
    if n < 2 {
        return n
    } else {
        return fib(n-1) + fib(n-2)
    }
}

fib(x: 10) // 55

// (Note the name 'x' should not be required here.
//  It seems seems to be a bug in Beta 3, since the curried function in the
//  Swift guide doesn't work as advertised either.)
Run Code Online (Sandbox Code Playgroud)