call generic function without params

222 Views Asked by At
protocol IDataSource:AnyObject{
    typealias DS;
    typealias U;
    func dataSource(ds:DS, index:Int?);
    func dataSource(ds:DS, data:[U]);
}

class DataSource<T:AnyObject>{

    var map = [NSManagedObjectID:T]();
    var data = [T]();
    var ctrls:NSHashTable = NSHashTable.weakObjectsHashTable();
    func find(value:T)->Int?;
    var selected:T?;

    func setNeedsUpdate<Bar:IDataSource where Bar.U==T,Bar.DS==DSGen>(){
        for ctrl in self.ctrls.allObjects {
            let client = ctrl as! Bar;
            client.dataSource(self, data:self.data);
        }
    }
    func foo(){
        // error
        setNeedsUpdate()    
    }
}

How I can call method setNeedsUpdate()? compiler error " Cannot invoke 'setNeedsUpdate' with no arguments"

2

There are 2 best solutions below

0
On

have found some decision, but decision demand extra parameter

func setNeedsUpdate<Bar:IDataSource where Bar.U==T,Bar.DS==DSGen>(type:Bar.Type){
    for ctrl in self.ctrls.allObjects {
        let client = ctrl as! Bar;
        client.dataSource(self, data:self.data);
    }
}
func foo<Bar:IDataSource where Bar.U==T,Bar.DS==DSGen>(){
    // error
    setNeedsUpdate(Bar.self)    
}
4
On
func setNeedsUpdate<Bar:IDataSource where Bar.U==T,Bar.DS==DSGen>(){

You can declare a generic function like this, but in isolation you can never call it, because you have provided no way to specify the generic placeholder. In other words, there is nothing here that would tell the compiler what type Bar actually is. Thus, as it stands, this is a useless function.

I think the first thing to ask yourself might be why this needs to be a generic at all - and why, indeed, the class DataSource needs to be a generic. If you know that ctrls will be hash table consisting of IDataSources, it's hard to see what the generic is for. It's not clear what you're trying to accomplish but it seems that you might be overthinking it.