I have had a similar problem previously and someone suggested keypaths might be the answer
I want to add to the number of blueBandages
The obvious way is the following:
But this will require a lengthy If statement to identify which item to add. I will have to add to the if statement every time I add an item to the catalog
I wish I could "unwrap" some string as executable code, but I don't think this exists.
Maybe keypaths are the answer? I haven't been able to make it work, because my key path is still acting like a string and not executable code
I want to add to the number of blueBandages
Code Block struct Product { var brand: String var option1: String var option2: String var item1: String var item2: String } //inventory var blueBandages = 0 var redBandages = 0 var yellowBandages = 0 var greenBandages = 0 //catalog let products = [ Product(brand: "Academia", option1: "Blue", option2: "Red", item1: "blueBandages", item2: "redBandages"), Product(brand: "Academia", option1: "Yellow", option2: "Green", item1: "yellowBandages", item2: "greenBandages")] func buy() { //??? }
The obvious way is the following:
Code Block func buy() { blueBandages += 1 }
But this will require a lengthy If statement to identify which item to add. I will have to add to the if statement every time I add an item to the catalog
Code Block var selectedProduct = 0 if selectedProduct == "Academia blueBandages": blueBandages += 1
I wish I could "unwrap" some string as executable code, but I don't think this exists.
Code Block func buy() { Code(product[1].item1) =+ 1 } //if only this worked the same as the previous code chunk
Maybe keypaths are the answer? I haven't been able to make it work, because my key path is still acting like a string and not executable code
If you want to choose the item with an integer value, you should better use Array:I would have to put in an If or Switch statement to input the correct ending, but this can get messy.
Code Block struct Product { var brand: String var option1: String var option2: String var items: [String] } var inventory: [String: Int] = [ "blueBandages": 0, "redBandages": 0, "yellowBandages": 0, "greenBandages": 0 ] //catalog let products = [ Product(brand: "Academia", option1: "Blue", option2: "Red", items: ["blueBandages", "redBandages"/*,...*/]), Product(brand: "Academia", option1: "Yellow", option2: "Green", items: ["yellowBandages", "greenBandages"/*,...*/]), ]
Code Block @IBAction func buyButton(_ sender: UIButton) { let chosenItem = sender.tag let inventoryKey = products[productIndex].items[chosenItem] //... inventory[inventoryKey, default: 0] += 1 }