Search code examples
swiftcocoa

Using a Swift struct in an NSOutlineView


I'm trying to populate an NSOutlineView with Swift structs as its items. This works, except for the row(forItem:) method, which always returns -1. I've made sure my struct conforms to Equatable and I implemented an isEqual function. Still the NSOutlineView can not find the row for any item.

If I convert my struct to a class (not derived from NSObject), it all works. Even without conforming to Equatable or implementing any isEqual functions.

I thought classes and structs in Swift are basically the same except one being a reference type and the other a value type.

What do I need to implement to use Swift structs as items in an NSOutlineView?


Solution

  • Someone posted a similar question on the Apple Developer Forum.

    NSOutlineView doesn't use Equatable when identifying an item, it uses the reference pointer to the item. In Swift, structs are always passed by value (and not passed by reference) so the outline view will never recognize that the item you're passing is the same. Switching your struct to a class fixes the issue because Swift uses pass by reference for classes.

    Unfortunately, there's no way to use Structs as items to work with NSOutlineView and you will need to use a Class.

    Read this answer for more details about how Swift uses pass by reference vs. pass by value.