钵钵鸡实力代购
钵钵鸡实力代购

Reputation: 1042

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

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

Upvotes: 1

Views: 120

Answers (1)

matt
matt

Reputation: 535315

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)")
    }

Upvotes: 2

Related Questions