Brandon Brandon - 4 months ago 10
Swift Question

swift anonymous function recursion

I'm trying to write a function literal in swift with a recursive body - in this case it's simply to add all the values in a list. I'm getting an error that "Variable used within it's own initial value". Any thoughts on what might be wrong here? Also I'm aware that what I'm doing here is a simple reduce and that it's build into Array, I'm just using this as an illustrative example of what I'm seeing elsewhere.

let list: Slice = [1,2,3,4,5,6,7,8,9,10]

var closure = { (memo: Int, list: Slice<Int>) -> Int in
if (list.count == 0) {
return memo
} else {
return closure(memo + list[0], list[1..<list.count])
}
}

let value = closure(0,list)

Answer

Try this:

let list: Slice = [1,2,3,4,5,6,7,8,9,10]

var closure:((Int, Slice<Int>) -> Int)!
closure = { (memo, list) in
    if (list.count == 0) {
        closure = nil // remove retain cycle
        return memo
    } else {
        return closure(memo + list[0], list[1..<list.count])
    }
}

let value = closure(0, list)

EDIT:

see this video: Advanced Swift at WWDC14. from around 41:00. it shows the down side of this method, and better workaround.