Search code examples
swiftxcodecocoansoutlineview

Get multiple items from Cocoa NSOutlineView using selectedIndexSet in Swift


When I need to get the selected item from a NSOutlineView I can just use this:

func item(atRow row: Int) -> Any?

But how do I get a list of items when using multiple selections? I can use

var selectedRowIndexes: IndexSet { get }

to get an IndexSet but isn't there an implemented way to get an array of the selected items?

Thanks for any advise


Solution

  • Map the rows to the items, compactMap unwraps the optionals safely.

    let selectedItems = outlineView.selectedRowIndexes.compactMap{outlineView.item(atRow: $0)}
    

    outlineView is the reference to the NSOutlineView

    The result is an array of Any. You can cast the type either in the closure or at the end of the line.