My app got a memory issue. The code was like
func foo() {
var bar = [String:[String]]()
....
#if DEBUG
bar.keys.sorted().forEach { key in
print(key, "\t", bar[key]!)
}
#endif
Since there was a memory issue, I decided to move the bar to be a class instance variable and free it every time.
class some {
lazy private var bar = [String:[String]]()
func foo() {
defer {
bar..removeAll(keepingCapacity: true)
}
....
#if DEBUG
bar.keys.sorted().forEach { key in
print(key, "\t", bar[key]!)
}
#endif
However, the second code crashed immediately after the app ran on print(key, "\t", bar[key]!)
.
The reason of the crash was because the bar was already empty, which was not expected by me. So the forEach must be ran asyncronously. And the removeAll ran first.
I could fix the app by changing forEach to for-loop, but I wanted to make sure my thinking was right or not.