2015-11-15 47 views
4

代碼在操場這裏如何使用仿製藥PARAMS(雨燕2.0)

class ProductModel { 
    var productID : Int = 0 
    init(id:Int) { 
     productID = id 
    } 
} 


protocol GenericListProtocol { 
    typealias T = ProductModel 
    var list : [T] { get set } 
    var filteredlist : [T] { get set } 
    func setData(list : [T]) 
} 
extension GenericListProtocol { 
    func setData(list: [T]) { 
     list.forEach { item in 
      guard let productItem = item as? ProductModel else { 
       return 
      } 
      print(productItem.productID) 
     } 
    } 
} 

class testProtocol { 
    class func myfunc<N:GenericListProtocol>(re:N){ 
     var list : [ProductModel] = [ProductModel(id: 1),ProductModel(id: 2),ProductModel(id: 3),ProductModel(id: 4)] 
     re.setData(list) 
    } 
} 

但在該行re.setData(list)

得到編譯錯誤:

Cannot convert value of type '[ProductModel]' to expected argument type '[_]'.

我的問題是如何在GenericListProtocol中使用setData方法?

任何人都可以幫助將不勝感激。

回答

2

ProductModel類型移入擴展並從通用協議中刪除約束似乎可行。

class ProductModel { 
    var productID : Int = 0 
    init(id:Int) { 
     productID = id 
    } 
} 

protocol GenericListProtocol { 
    typealias T 
    var list : [T] { get set } 
    var filteredlist : [T] { get set } 
    func setData(list : [T]) 
} 

extension GenericListProtocol { 
    func setData(list: [ProductModel]) { 
     list.forEach { item in 
      print(item.productID) 
     } 
    } 
} 

class testProtocol { 
    class func myfunc<N:GenericListProtocol>(re:N) { 
     let list : [ProductModel] = [ProductModel(id: 1),ProductModel(id: 2),ProductModel(id: 3),ProductModel(id: 4)] 
     re.setData(list) 
    } 
} 
+0

謝謝,我真的更新與泛型.. –

+0

樂於幫助。這是一個很好的例子。 – Daniel

0

我發現這個問題很有趣,並且認爲我們可以用通用的方式解決這個問題。

protocol Product { 
    var productID : Int {get set} 
} 

class ProductModel: Product { 
    var productID : Int = 0 
    init(id:Int) { 
     productID = id 
    } 
} 

protocol GenericListProtocol { 
    typealias T : Product 
    var list : [T] { get set } 
    var filteredlist : [T] { get set } 

} 

extension GenericListProtocol { 
    func setData(list: [T]) { 
     list.forEach { item in 
      print(item.productID) 
     } 
    } 
} 

class GenericListProtocolClass : GenericListProtocol 
{ 
    typealias T = ProductModel 
    var intVal = 0 

    var list = [T]() 
    var filteredlist = [T]() 

} 

class testProtocol { 
    class func myfunc(re: GenericListProtocolClass){ 
     let list : [ProductModel] = [ProductModel(id: 1),ProductModel(id: 2),ProductModel(id: 3),ProductModel(id: 4)] 
     re.setData(list) 
    } 
} 


let temp = GenericListProtocolClass() 
testProtocol.myfunc(temp) 

欣賞您的想法和建議,如果它可以進一步改善。