Swift: 感受闭包

func addCollect(item: CollectItem, myClosure: (Bool -> Void))  {
        self.myQueue?.inDatabase({
        //闭包, 是异步 执行地
        //在闭包里面 ,没有办法 返回 方法的返回值,   所以不能用 外部变量
        (db) in
            let insertSql = "insert into collect (applicationId, name, imageData) values (?, ?, ?)"
            let data = UIImagePNGRepresentation(item.image!)
            let flag = db.executeUpdate(insertSql,withArgumentsInArray: [item.applicationId!, item.name!, data!])                
            if flag == false{
             print(db.lastErrorMessage())
            }
            myClosure(flag)
              })        
    }

佐证

//    var downloadFinishedClosure: ((NSData)->Void)?
    // 不行的,闭包不是这么用的。
//    var downloadFailedClosure: ((NSError)->Void)?
    //MARK:-   用代理 处理下载
unc downloadInClosureWithUrlString(urlString: String, downloadFinishedClosure: ((NSData)->Void)?, downloadFailedClosure: ((NSError)->Void)?){
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)    
        let session = NSURLSession.sharedSession()   
        let task = session.dataTaskWithRequest(request) { (data, response, error)            
            in            
            if error == nil {            
                let httpResponse = response as! NSHTTPURLResponse                
                if httpResponse.statusCode == 200{               
                    downloadFinishedClosure!(data!)                                  
                }else{                               
                    let errorDIY = NSError(domain: urlString, code: httpResponse.statusCode, userInfo: ["message":"有错误"])
                    downloadFailedClosure!(errorDIY)                
                }            
            }            
        }    
        task.resume()        
    }

你可能感兴趣的:(Swift: 感受闭包)