2015-05-09 36 views
0

我有一个自定义控件使用数据源来获取项目(就像NSTableView所做的那样)。数据源可以返回任何类型,只要它是可散列的。这些项目被用作私人字典中的密钥。nil不可转换为可散列。

控件(自定义视图)被添加到界面构建器中的UI中。

由于nil不能转换为可散列,所以当我用nil参数查询数据源时遇到问题。

这样做的正确方法是什么?

protocol DataSourceProtocol 
{ 
    func numberOfChildrenOfItem<Item: Hashable>(item: Item?) -> Int 
    func child<Item: Hashable>(index: Int, ofItem item: Item?) -> Item 
} 

class MyControl : NSControl 
{ 
    var dataSource : DataSourceProtocol! 

    func reloadData() 
    { 
    //using string as an example of a hashable 
    let countA = dataSource.numberOfChildrenOfItem("item") // ok 
    let countB = dataSource.numberOfChildrenOfItem(nil)  // not ok 

    let childA = dataSource.child(0, ofItem: "item") //ok 
    let childB = dataSource.child(0, ofItem: nil) //not ok 
    self.reloadChildren(childA) 
    self.reloadChildren(childB) 
    } 

    func reloadChildren<Item: Hashable>(item: Item) 
    {} 

}

回答

1

使用NSNull()得到一个空的对象,然后你就可以比较不同的NSNull()来看看它的空。

+1

这不是很快捷,是吗? – user965972

+1

@ user965972无论如何,你不能将nil作为对象传递,所以你不能对此做任何事情:p – Schemetrical