are there any workaround to specify inner func capture list & their modifier in swift

123 views Asked by At

i searched the swift spec for capture list on inner func but without luck, is there any way to break these kind of reference cycle?

class Hello {
    var name = "name"
    var fn: (()->())? = nil
}

func foo() -> Hello? {
    var bar: Hello? = Hello()
    func wrapper() -> () -> () {
        func inner() {
            print("bar: \(bar)")
        }
        return inner
    }
    bar?.fn = wrapper()
    return bar
}

var s = foo()
var b = Hello()

isKnownUniquelyReferenced(&s)  // false
isKnownUniquelyReferenced(&b)  // true
1

There are 1 answers

0
matt On BEST ANSWER

To use a capture list, you have to use an anonymous function (what many people wrongly call a "closure"). So, you would rewrite your

    func inner() {
        print("bar: \(bar)")
    }

as

    let inner : () -> () = { [weak bar] in
        print("bar: \(bar)")
    }