0

I have a custom control that is using a datasource to fetch items (as an NSTableView would do). The datasource can return Any-type, as long as it's hashable. The items are used as a key in a private dictionary.

The control (custom view) is added to the UI in interface builder.

I run into problems when I am querying the datasource with a nil parameter because nil is not convertible to hashable.

What is the proper way to do this?

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

}

4

1 回答 1

1

Use NSNull() to get a null object, which you can then compare to another NSNull() to see if its empty or not.

于 2015-05-09T12:11:11.170 回答