Skip to content

Instantly share code, notes, and snippets.

@mehmetfarhan
Created September 25, 2020 11:18
Show Gist options
  • Save mehmetfarhan/a938a6c42dcf3de4b979cece2e11efe1 to your computer and use it in GitHub Desktop.
Save mehmetfarhan/a938a6c42dcf3de4b979cece2e11efe1 to your computer and use it in GitHub Desktop.
Capture List
import UIKit
final class Increment {
// MARK: - Properties
private var number: Int = 0
// MARK: - This will cause memory leak
// lazy var incrementNumber: (Int) -> Void = { value in
// self.number += value
// print(self.number)
// }
// MARK: - If I instantiate increment(), then I immediately call increment with a three, the program will crash, because when the stored property has returned, the object (increment instance) can be deallocated, nothing else is referring to it.
// lazy var incrementNumber: (Int) -> Void = { [unowned self] value in
// self.number += value
// print(self.number)
// }
// MARK: - This will not cause memory leak
lazy var incrementNumber: (Int) -> Void = { [weak self] value in
guard let self = self else { print("Sorry I am did disappear") ; return }
self.number += value
print(self.number)
}
deinit {
print(#function)
}
}
// MARK: - Test
do {
let increment = Increment().incrementNumber(3)
}
/*
deinit
Sorry I am did disappear
*/
do {
let increment = Increment()
increment.incrementNumber(3)
}
/*
3
deinit
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment