In a lot of sample, people use closures to pass a function as a parameter :
sum.getSumOf(array: [1,2,3]) { [weak self] sum in
self?.result = sum
print(self?.result as Any)
}
I understand that is done for cycling issues. But what about passing a function rather than a closure ? How make this function "weak" ?
For example:
class Calculator {
let sum = Sum()
var result = 0
// passing a function
func doSum() {
sum.getSumOf(array: [1,2,3], handler: store(sum:))
}
// vs use closure
func doSumWeakSelf() {
sum.getSumOf(array: [1,2,3]) { [weak self] sum in
self?.result = sum
print(self?.result)
}
}
func store(sum:Int){
result = sum
print(result)
}
}
class Sum {
func getSumOf(array:[Int], handler: ((Int)->Void)) {
//step 2
var sum: Int = 0
for value in array {
sum += value
}
handler(sum)
}
}