0

Hy guys,

I have these source code

let downloadTask = session.downloadTaskWithURL(url,
completionHandler: {
  [weak button] url, response, error in
    if error == nil && url != nil {
      if let data = NSData(contentsOfURL: url) {
        if let image = UIImage(data: data) {
          dispatch_async(dispatch_get_main_queue()) {
            if let button = button {
              button.setImage(image, forState: .Normal)
            }
          }
        }
      }

This block of code try to put image from url in button element. Can someone help me to understand why in this source code block, in the completionHandler parameters list it use [weak button]? What's the meaning of [weak ...] and why use it? ( I think to avoid retain cycle.) Thank you guys!

Alessio Marzoli
  • 167
  • 2
  • 3
  • 10
  • A side note: don't check `error == nil`, it is not guaranteed to be `nil` in case of successful operation http://stackoverflow.com/a/1810301/2128900 – Michał Ciuba Dec 12 '14 at 11:17
  • see the apple docs: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html#//apple_ref/doc/uid/TP40014097-CH20-XID_103 – rintaro Dec 12 '14 at 11:32

2 Answers2

0

It's not a parameter it just declaration that every call to button in the function is to weak reference of the button. This is a swift way to use a weak reference to an object inside closure.

This is equivalent to Objective-C:

UIButton * __weak button = ...
Greg
  • 25,317
  • 6
  • 53
  • 62
0

[weak button] means that the button parameter is optional, it can be nil when the completion handler is executed. So there is a possibilty that the button is not existing in the completion block. You could use [unowned button] as well, but only when you are sure that the button is exists, otherwise it will chrash. And the third option is that you dont use neithor weak nor unowned before the button, which means that until the closure is executed, it will keep a strong reference to the button and doesnt let it to be deinited.

Dániel Nagy
  • 11,815
  • 9
  • 50
  • 58