0

I have couple of questions about the structure of the following code.I assume progressBlock and completionhandlers are callback functions passed to downloadWithDownloadType function. Is my assumption correct? And What does [weak Self] before function parameters do? In what situation do you need that?

func downloadContent(key: String, pinOnCompletion: Bool) {

            let manager = AWSUserFileManager.defaultUserFileManager()
            let content = manager.contentWithKey(self.prefix + key)

            content.downloadWithDownloadType(
                .IfNewerExists,
                pinOnCompletion: pinOnCompletion,
                progressBlock: {[weak self](content: AWSContent?, progress: NSProgress?) -> Void in
                    guard self != nil else { return }
                    /* Show progress in UI. */
                },
                completionHandler: {[weak self](content: AWSContent?, data: NSData?, error: NSError?) -> Void in
                    guard self != nil else { return }
                    if let error = error {
                        // Handle Error
                        return
                    }
                    if let fileData = data {
                        let rawData = NSString(data: fileData, encoding:NSUTF8StringEncoding) as! String
                       // Do something

                    }
                    //Download Complete
                })
        }
KMC
  • 1,677
  • 3
  • 26
  • 55
  • `[weak self]` is a *capture list* for the closure. Have a look at „Resolving Strong Reference Cycles for Closures“ in the Swift Language Reference. – Martin R Dec 17 '16 at 09:51
  • 1
    This tutorial is amazing: read [here](http://alisoftware.github.io/swift/closures/2016/07/25/closure-capture-1/) to understand **capturing** and the nature of closures. Then read [here](http://stackoverflow.com/questions/32665326/reference-to-property-in-closure-requires-explicit-self-to-make-capture-seman/40530556#40530556) to better understand what weak does. Finally for a good overview read [here](http://stackoverflow.com/questions/24320347/shall-we-always-use-unowned-self-inside-closure-in-swift) – mfaani Dec 17 '16 at 13:19
  • and Apple's own documentation [here](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html) – mfaani Dec 17 '16 at 13:23

0 Answers0