How to use generics as params? (Swift 2.0)

The code on the playground is here

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)
    }
}

But in line re.setData(list)

get compilation error:

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

My question is: how to use setData's method GenericListProtocol?

Anyone who can help would be appreciated.

+4
source share
2 answers

Moving a type ProductModelinto an extension and removing a constraint from a common protocol seems to work.

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)
    }
}
+2
source

I found this question interesting and thought how best we could solve it in a general way.

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)

Evaluate your thoughts and suggestions if they can be improved.

0
source

Source: https://habr.com/ru/post/1615941/


All Articles