2015-04-02 30 views
1

我想在圖像下載完成後設置圖像變量。我正在使用'inout'將圖像變量傳遞給我的下載函數,但它沒有設置。Swift inout沒有設置

這裏是我的代碼:

var img: UIImage? 

func downloadImage(url: String?, inout image: UIImage?) { 

    if url != nil { 

     var imgURL: NSURL = NSURL(string: url!)! 
     var request: NSURLRequest = NSURLRequest(URL: imgURL) 

     NSURLConnection.sendAsynchronousRequest(request, queue: 
      NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!, 
      data: NSData!,error: NSError!) -> Void in 

      if error == nil { 
       dispatch_async(dispatch_get_main_queue(), { 

        // setting img via inout doesn't work 
        image = UIImage(data: data) // inout img should be set but its not 
        println(img) 

        // setting img directly works, but don't want it hard coded 
        img = UIImage(data: data) 
        println(img) 

       }) 
      } 
      else { 
       println("Error") 
      } 
     }) 
    } 
} 

downloadImage(<<IMAGE URL HERE>>, &img) // passing img as an inout 

林期待變量img這是作爲一個INOUT的圖像被下載後,設置的downloadImage功能過去了,但它永遠不會被更新。

我期待行:image = UIImage(data: data)來更新IMG INOUT變量,但它沒有。

但是,直接引用img變量的行:img = UIImage(data: data)被更新。

但我不想直接在函數中硬編碼img變量,我希望能夠通過inout傳遞任何我想要的變量。

任何想法,爲什麼我不能更新inout變量,以及如何解決它。 謝謝。

+1

異步代碼不會同步運行。 – nhgrif 2015-04-02 01:09:08

+0

你的評論是不是很有幫助 - 一些意見,將不勝感激 – Bingo 2015-04-02 01:12:53

+0

您的功能運行異步代碼。異步塊中的代碼在函數返回之前不會完成。除了期望在函數返回之前完成異步代碼之外,代碼沒有任何問題。 – nhgrif 2015-04-02 01:13:36

回答

2

您需要將「延續」傳遞給您的downloadImage()函數;延續是做什麼用下載的圖像:像這樣:

func downloadImage(url: String?, cont: ((UIImage?) -> Void)?) { 
    if url != nil { 

    var imgURL: NSURL = NSURL(string: url!)! 
    var request: NSURLRequest = NSURLRequest(URL: imgURL) 

    NSURLConnection.sendAsynchronousRequest (request, 
     queue:NSOperationQueue.mainQueue(), 
     completionHandler: { 
      (response: NSURLResponse!, data: NSData!,error: NSError!) -> Void in 
      if error == nil { 
      dispatch_async(dispatch_get_main_queue(), { 
       // No point making an image unless the 'cont' exists 
       cont?(UIImage(data: data)) 
       return 
      }) 
      } 
      else { println ("Error") } 
     }) 
    } 
} 

,然後你使用這樣的:

var theImage : UIImage? 

downloadImage ("https://imgur.com/Y6yQQGY") { (image:UIImage?) in 
    theImage = image 
} 

在那裏我已經利用語法尾隨關閉和簡單地分配可選,下載的圖像到所需的變量。

另外,請注意,我沒有檢查過你的線程結構;它可能是cont函數應該在其他一些隊列上調用 - 但是,你會得到延續的傳遞點。

+0

謝謝。我不確定這個解決方案是否有效,它會使操場崩潰。你能運行它嗎? – Bingo 2015-04-02 02:26:51

+0

我得到一個編譯器錯誤的dispatch_async行:不能用類型'(dispatch_queue_t!,() - () - > $ T3)'參數列表調用'init''...任何想法如何解決這個問題? – Bingo 2015-04-02 02:33:08

+0

在'cont?()'行後面添加'return'。類型推理器已經決定'cont?()'可能會返回一些不應該的東西。 – GoZoner 2015-04-02 02:34:33