1
votes

I've got an NSComboBox in my app, and I'd like it to display the contents of an array per line from a multi-dimensional array, rather than an element from a one-dimensional array.

My ViewController conforms to NSComboBoxDataSource, has the two required methods (numberOfItems and objectValueForItemAt index), and within viewDidLoad() I've set:

myComboBox.usesDataSource = true 
myComboBox.dataSource = self

Everything works perfectly with a one-dimensional array.

I've got the following array:

var testArray: [[String]] = [["Array 1", "Element"],["Array 2", "Element"]]

followed by the following functions later on:

func numberOfItems(in comboBox: NSComboBox) -> Int {
    return testArray.count
}

func comboBox(_ comboBox: NSComboBox, objectValueForItemAt index: Int) -> Any? {
    return testArray[index]
}

Please see the attached screengrab for what my NSComboBox returns (which is just '(' on each line). I had expected the first line to return ["Array 1", "Element"] and the second line to return ["Array 2", "Element"]. Ideally I'd want the NSComboBox to return only the contents of the arrays like so: Array 1, Element (i.e. without [ ] and ")

The closest I've got is by trimming characters as follows:

    func comboBox(_ comboBox: NSComboBox, objectValueForItemAt index: Int) -> Any? {

    return String(describing: testArray[index]).trimmingCharacters(in: CharacterSet(charactersIn: "[]\""))
}

But that returns Array 1", "Element, so if anyone has any suggestions for why it hasn't trimmed all the \" that would be appreciated too.

I'm new to Swift so apologies if I've missed something obvious!

Thanks in advance.

The NSComboBox return without string trimming

The NSComboBox return with string trimming, but including a couple of rogue \"

1

1 Answers

1
votes

If you want to control the String representation, you should better not modify the output of String.init(describing:).

And trimmingCharacters(in:) trims the both ends of a String.

Try something like this:

func comboBox(_ comboBox: NSComboBox, objectValueForItemAt index: Int) -> Any? {
    return testArray[index].joined(separator: ", ")
}