Wednesday, March 25, 2015

Overview

Closures are awesome. You can do some powerful things with them, but they are dangerous sometimes. You can find more information about closures here.

Content

Here’s an example where the closure will create a memory leak.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Person {
    var batmanSong = {} // () -> ()
    var sing(value: String) {
        println(value)
    }
    func learnSomething() {
        var na = "Na"
        var batman = " Batman"
        batmanSong = {
            na += "Na"
            self.sing(na + batman)
        }
    }
    func singBatmanSong8Times() {
        for i in 1...8 {
            sing()
        }
    }
}

The problem is that self has a reference to batmanSong and batmanSong has a reference to self. To fix this problem, you just say that batmanSong shouldn’t keep a reference to self.

1
2
3
4
batmanSong = { [unowned self] in
    na += "Na"
    self.sing(na + batman)
}

Random Posts