2015-10-24 104 views
1

我正在創建一個函數以用於不同的場合。但爲此,我需要將一個函數的返回值轉換爲在此主函數中作爲泛型傳遞的Object。將對象投射到通用

func makeRequestToApi<T>(object: T, url: String) { 
    Alamofire.request(.GET, url).responseJSON { request in 
     if let json = request.result.value { 
      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) { 
       let data = JSON(json) 
       let object: [T] = self.createProductObject(data) as Any as! [T] 

       dispatch_async(dispatch_get_main_queue()) { 
        self.delegate?.networkingDidUpdate(object) 
       } 
      } 
     } 
    } 
} 

我想我只需要調用是這樣的:

networkingController.makeRequestToApi(Product, url: Urls.menu)

該函數將返回的產品self.createProductObject(data) -> [Product]

但是,一個陣列的Xcode讓我補充.self第一個參數in makeRequestToApi

networkingController.makeRequestToApi(Product.self, url: Urls.menu)

這樣,我看到,Swift不會將我的類的返回值轉換爲Product,因爲我需要它。

任何人都知道我需要做什麼?

謝謝。

回答

0

你可能想是這樣的:

func makeRequestToApi<T>(create: JSON -> [T], url: String) { 
    Alamofire.request(.GET, url).responseJSON { request in 
     if let json = request.result.value { 
      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) { 
       let data = JSON(json) 
       let object = create(data) 

       dispatch_async(dispatch_get_main_queue()) { 
        self.delegate?.networkingDidUpdate(object) 
       } 
      } 
     } 
    } 
} 

makeRequestToApi(createProductObject, url: Urls.menu) 

編輯:這編譯爲我(你可能需要調整您的委託方法):

import Foundation 

struct Product {} 

protocol Delegate : class { 
    func networkingDidUpdate<T>(obj: [T]) 
} 

class Test { 
    weak var delegate : Delegate? 

    func makeRequestToApi<T>(create: JSON -> [T], url: String) { 
     Alamofire.request(.GET, url).responseJSON { request in 
      guard let json = request.result.value else { return } 

      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) { 

       let object = create(JSON(json)) 

       dispatch_async(dispatch_get_main_queue()) { 
        self.delegate?.networkingDidUpdate(object) 
       } 
      } 
     } 
    } 

    func createProductObject(json: JSON) -> [Product] { 
     return [Product()] 
    } 
} 


let test = Test() 
test.makeRequestToApi(test.createProductObject, url: "")