Is there a way to make NSMenuItem representing a dictionary in Swift?

402 Views Asked by At

When a user selects a menu item in NSPopUpButton, I want this item to be representing a dictionary, not just its String value, but still displaying a String. I created a for-in loop to compare dictionaries, but I want to compare only dictionaries that are selected in the differents NSPopUpButton.

I tried to create an array of the selected items like this :

var selection = [listOne!.selectedItem!, listeTwo!.selectedItem!, listThree!.selectedItem!, listFour!.selectedItem!, listFive!.selectedItem!]

And I set 'selection' as the for-in loop target. But of course it doesn't work because I created an array of NSMenuItem type, and what I want is to use my loop with the dictionaries that are represented by the menu items, not with the menu item itself. For now my menu items are displaying their string values, but I also need them to be representing dictionaries that are linked to them. So how can I do that ? I tried many ways but none of them was working.

Here are my dictionaries and the declaration of my two ingredients :

var ingredientListMettinaCommon = [
    catClawBark: ["Resist Lightning": 5, "Resist Damage": 8],
    grapeHolly: ["Resist Poison": 6, "Resist Damage": 2]
]

var catClawBark = "Cat's Claw Bark"
var grapeHolly = "Grape Holly"

Here is the code line that fills my pop-up menu :

listOne.addItems(withTitles: Array(ingredientListMettinaCommon.keys))

And Here is my loop :

for (ingredient, keys) in selection { //Error : "Expression type '[NSMenuItem]' is ambiguous without more context"
for key in keys {
    for (ingredient2, keys2) in selection {
        for key2 in keys2 {
            if ingredient != ingredient2 {
                if key.key == key2.key {
                    result = "You created a potion !\n---> \(key.key) \(key.value + key2.value) <---"
                }
                else {
                    result = "No match. Check the ingredients selected or retry when you have more !"
                }
            }
        }
    }
}
}

So actually it's not working because my menu items (catClawBark and grapeHolly) are just linked to strings : "Cat's Claw Bark" and "Grape Holly", and not also to dictionaries that are in 'ingredientListMettinaCommon', so I wish to find a solution.

EDIT: Thanks to @vadian the problem is almost solved, but I still get some errors that I can't solve by myself. Instead of using the addItems(withTitles:) method, I put this loop :

for (ingredient, effect) in ingredientListMettinaCommon {
        let menuItem = listOne.addItem(withTitle: ingredient);
        menuItem.representedObject = [ingredient: effect] //ERROR on 'menuItem'
        }

But I get an error : Value of tuple type 'Void' has no member 'representedObject'

The constant menuItem is inferred to have type Void because of the addItem(withTitle:) method.

0

There are 0 best solutions below