I’ve just discovered that Swift has pointers like C. I am trying to make this code work, and the only way I did is by making a local copy.
This one is working fine.
func myMult(_ x: Int, _ yThunk: @escaping () -> Int) -> Int {
if x == 0 {
return 0
} else if x == 1 {
return yThunk()
} else {
return yThunk() + myMult(x - 1, yThunk)
}
}
func myDelay(_ th: @escaping () -> Int) -> (Bool, () -> Int) {
return (false, th)
}
func myForce(_ p: inout (Bool, () -> Int) ) -> Int {
let local_p = p.1()
if p.0 {
return p.1()
} else {
p.0 = true
p.1 = { local_p }
}
return p.1()
}
// (true, (Function))
var myDelayedResult = myDelay({2 + 3})
// false
delayedResult.0
// 5
delayedResult.1()
// 1500
myMult(300, {myForce(&delayedResult)})
Now, if I remove the local_p, I will get an error.
I am studying C, and C has declaring a point and dereferencing a pointer, and also the operator to obtain the memory address of a variable.
ChatGPT explanation:
- Swift requires that escaping closures do not capture inout parameters because inout parameters are only valid for the duration of the function call. Storing an inout parameter in an escaping closure would create a potential for invalid memory access.
func myForce(_ p: inout (Bool, () -> Int) ) -> Int {
if p.0 {
return p.1()
} else {
p.0 = true
// error: Escaping closure captures 'inout' parameter 'p'
p.1 = { p.1() }
}
return p.1()
}
Now with that in mind, my question is, do I need to dereference p? I tried p.1 = { inout p.1() } but I receive an error.
Found this one Escaping closure captures ‘inout’ parameter but it still do not answer my question.
Any explanation would be nice.