Post

Replies

Boosts

Views

Activity

Reply to Searching for the position of an item in an array within an array?
It was working in the playground but not the app. As I thought I had used the code incorrectly :). With some work I got it to function in the app too. Here is how it looks now:         let button = UIButton()         button.addTarget(self, action: #selector(self.selectTack(sender:)), for: .touchUpInside)             let filteredProducts = products.filter { $0.item.contains(key)}             for product in filteredProducts {                 if let itemPosition = product.item.firstIndex(of: key) {                     let foundColor = product.colorName[itemPosition]                     if value > 0 {                     button.setTitle("\(foundColor) \(product.brand) \(product.category), amount: \(value)", for: UIControl.State.normal)                     tackStack.addArrangedSubview(button)                 }             }         }     }
Topic: Programming Languages SubTopic: Swift Tags:
Jan ’21
Reply to Searching for the position of an item in an array within an array?
Thanks, testing it out now. the product below shows four different items: Product(brand: "Academia", category: "Bandages", colorName: [ "Blue", "Green", "Purple", "Red" ], item: ["academiaBandagesBlue", "academiaBandagesGreen", "academiaBandagesPurple", "academiaBandagesRed"]) So the following identifies which item of the selected product the view will show        // What is the position of key in item list (there should be only one ? //If color are in the same order than item, then we got it The colors are in the same order of the items I am trying to use the inventory to populate a stackView of buttons, showing the amount of each item. However, I might have some error as it is showing up different items each time. Is this because dictionaries don't show things in a specific order? Maybe I should change the tackInventory into an array also... struct Tack { var item: String var amount: Int } var tackInventory = [ Tack(item: "academiaBandagesBlue", amount: 2) Tack(item: "academiaBandagesRed", amount: 5) ]
Topic: Programming Languages SubTopic: Swift Tags:
Jan ’21
Reply to Using keypaths to add a value to a variable?
It's working now! I had a small typo :) Thanks for the help! import UIKit struct Product {     var brand: String     var option: [String]     var item: [String] } var inventory: [String: Int] = [     "blueBandages": 0,     "redBandages": 0,     "yellowBandages": 0,     "greenBandages": 0 ] //catalog let products = [     Product(brand: "Academia", option: ["Blue", "Red"], item: ["blueBandages", "redBandages"]),     Product(brand: "Academia", option: ["Yellow", "Green"], item: ["yellowBandages", "greenBandages"]) ] let productIndex = 1 let chosenItem = 1 let inventoryKey = products[productIndex].item[chosenItem]     print(products[productIndex].item[chosenItem])     print(inventory[inventoryKey, default: 0])       inventory[inventoryKey, default: 0] += 1     print(products[productIndex].item[chosenItem])     print(inventory[inventoryKey, default: 0])
Topic: Programming Languages SubTopic: Swift Tags:
Jan ’21
Reply to Using keypaths to add a value to a variable?
Using an array within the struct has helped a lot! I'll be editing a lot of my app if I can make this work. I'm having trouble changing the values in the dictionary though.         print(productIndex)         let inventoryKey = products[productIndex].item[chosenItem]         print(inventoryKey)         inventory[inventoryKey, default: 0] += 1    		print(inventoryKey) When I click a different product, the productIndex (productIndex = indexPath.row from previous VC) is correct, but the inventoryKey is always from productIndex = 0 regardless of what productIndex is clicked. It appears it is using the default value for productIndex; chosenItem is working correctly
Topic: Programming Languages SubTopic: Swift Tags:
Jan ’21
Reply to Using keypaths to add a value to a variable?
Ok, I have this now: productIndex created from the indexPath from the collectionView that contains the products in a previous VC. The color options for each items appear as buttons along the bottom (chosenItem) var productIndex = 0     @IBAction func buyButton(_ sender: UIButton) {         var chosenItem = sender.tag         let inventoryKey = products[productIndex].chosenItem                func buyButton() {             inventory[inventoryKey, default: 0] += 1         } however, I am not able to find the color choice (item1, item2) by putting in the var at the end of line 4. It tries to find the property chosenItem that does not exist. I would have to put in an If or Switch statement to input the correct ending, but this can get messy.                 var inventoryKey = products[productIndex].item1         switch sender.tag {         case 0:             inventoryKey = products[productIndex].item1         case 1:             inventoryKey = products[productIndex].item2         case 2:             inventoryKey = products[productIndex].item3         case 3:             inventoryKey = products[productIndex].item4         default:             inventoryKey = products[productIndex].item1         }             inventory[inventoryKey, default: 0] += 1             print(inventory["academiaBandagesBlue"]!)     
Topic: Programming Languages SubTopic: Swift Tags:
Jan ’21
Reply to Using keypaths to add a value to a variable?
Using a dictionary seems like a good idea, how can I change a value in the dictionary when updating amounts? struct Product {     var brand: String     var option1: String     var option2: String     var item1: String     var item2: String } var inventory: [String: Int] = [     "blueBandages": 0,     "redBandages": 0,     "yellowBandages": 0,     "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")] let brandKeyPath = \Product.brand print(products[1][keyPath: brandKeyPath]) print(brandKeyPath) func buy() {     brandKeyPath += 1 }
Topic: Programming Languages SubTopic: Swift Tags:
Jan ’21
Reply to Calling a property of a struct with a placeholder?
I don't think it can work in the trainHorse function after all, but there is still hope for the progress bar. This is updated every time the trainHorse button is pressed. skillProgress.progress = myHorses[horseIndex][keyPath: currentTraining]            skillOutlet.text = "\(currentScaleName): \(myHorses[horseIndex][keyPath: currentTraining])"        } The scalesButton updates the currentTraining var, then the trainHorse button updates skillProgress
Topic: Programming Languages SubTopic: Swift Tags:
Jan ’21
Reply to Calling a property of a struct with a placeholder?
the skill buttons are programmatically added when the user selects a scale.                     let button = UIButton()                     button.tag = skillIndex                     button.setTitleColor(.white, for: UIControl.State.normal)                     button.addTarget(self, action: #selector(self.trainHorse(sender:)), for: .touchUpInside)                     button.setTitle(currentScaleCode[skillIndex].name, for: UIControl.State.normal)                     button.backgroundColor =  colorLiteral(red: 0.005273803137, green: 0.4785152674, blue: 0.3960535526, alpha: 1)                     buttonsStack.addArrangedSubview(button)                 }          buttonsStack.translatesAutoresizingMaskIntoConstraints = false          These buttons trigger the trainHorse function, which updates a progress bar showing progress within the selected scale. For now it only shows .basicSkills because I have been unable to change this to anything else. If I could change the currentTraining key path to something different, I could update the progress bar programmatically with the trainHorse function. All I need to know is how to change the var currentTraining
Topic: Programming Languages SubTopic: Swift Tags:
Jan ’21
Reply to Calling a property of a struct with a placeholder?
There isn't space here to show the entire code, so I'm trying to collect the bits that count from different parts of the app. The VC I am working with shows a progress bar for each scale on each horse. When I use a lengthy If statement, it works the way it should. However, it requires a lot of extra coding. I wonder if key paths could be a way of shortening my code (in reality there are 7 possibilities instead of three). I think I can make key paths work if I can figure out how to change var currentTraining and var currentBoost. Then I can make an IBAction to change the var and thus make the progress bar show the training progress. For now it only shows basicTraining, because that is what I have manually written in the var currentTraining. I need to do this programmatically with the scalesButton. I think I managed to include everything now, please let me know if there is anything else missing struct Horse {&#9;&#9; var name: String&#9;&#9; var basicTraining : Float&#9;&#9; var rhythm : Float&#9;&#9; var suppleness : Float} var myHorses = [&#9;&#9; Horse(name: "Donnerhall", basicTraining : 0.5, rhythm : 0.2, suppleness : 0.1),&#9;&#9; Horse(name: "Bjork", basicTraining : 0.4, rhythm : 0.3, suppleness : 0.1)] var horseIndex = 0 struct Skill { var basicBoost: Float var rhythmBoost: Float var supplenessBoost: Float} var scaleCode = [ basicSkills, rhythmSkills, supplenessSkills] var scaleIndex = 0 var basicSkills = [Skill(basicBoost: 0.1, rhythmBoost: 0, supplenessBoost: 0)] var rhythmSkills = [Skill(basicBoost: 0, rhythmBoost: 0.1, supplenessBoost: 0)] var supplenessSkills = [Skill(basicBoost: 0, rhythmBoost: 0.1, supplenessBoost: 0.1)] var skillIndex = 0 var currentTraining: WritableKeyPath<Horse, Float> = \.basicTraining //or \.rhythm or \.suppleness var currentBoost: WritableKeyPath<Skill, Float> = \.basicBoost     @IBAction func scalesButton(_ sender: UIButton) {         scaleIndex = sender.tag         switch scaleIndex {         case 0:             currentTraining = \.basicTraining         case 1:             currentTraining = \.rhythm         case 2:             currentTraining = \.suppleness } //should choose&#9;.basicTraining, .rhythm, or .suppleness depending on which scalesButton the user selects.&#9;However, some skills can boost multiple stats, so I might have to do a separate if statement for each stat   @objc func trainHorse(sender: UIButton){       if myHorses[horseIndex][keyPath: currentTraining] >= 100 {         myHorses[horseIndex][keyPath: currentTraining] = 100         }  else  {         myHorses[horseIndex][keyPath: currentTraining] += currentScaleCode[skillIndex].currentBoost             } //previous code without key paths: //            if myHorses[horseIndex].basicTraining >= 100 { //                    myHorses[horseIndex].basicTraining = 100 //            } else  { //                    myHorses[horseIndex].basicTraining += currentScaleCode[skillIndex].basicBoost //            } // //            if myHorses[horseIndex].rhythm >= 100 { //                    myHorses[horseIndex].rhythm = 100 //            } else  { //                    myHorses[horseIndex].rhythm += currentScaleCode[skillIndex].rhythmBoost //            } // //            if myHorses[horseIndex].suppleness >= 100 { //                    myHorses[horseIndex].suppleness = 100 //            } else  { //                    myHorses[horseIndex].suppleness += currentScaleCode[skillIndex].supplenessBoost //            }         currentScaleCode = scaleCode[scaleIndex] //the following shows a progress bar with the stat selected with the scalesButton             skillProgress.progress = myHorses[horseIndex][keyPath: currentTraining]             skillOutlet.text = "\(currentScaleName): \(myHorses[horseIndex][keyPath: currentTraining])"         } previous code: //switch scaleIndex { //        case 0: //            skillProgress.progress = myHorses[horseIndex].basicTraining //            skillOutlet.text = "\(currentScaleName): \(myHorses[horseIndex].basicTraining)" //        case 1: //            skillProgress.progress = myHorses[horseIndex].rhythm //            skillOutlet.text = "\(currentScaleName): \(myHorses[horseIndex].rhythm)" //        case 2: //            skillProgress.progress = myHorses[horseIndex].suppleness //            skillOutlet.text = "\(currentScaleName): \(myHorses[horseIndex].suppleness)"
Topic: Programming Languages SubTopic: Swift Tags:
Jan ’21
Reply to Calling a property of a struct with a placeholder?
The app isn't working as intended, I printed to try to troubleshoot it. Can you show an example of how you would change the currentTraining variable? This is how I have tried to do it: var currentTraining: WritableKeyPath<Horse, Float> = \.basicTraining var scaleIndex = 0 IBAction with switch statement (scaleIndex is the same as sender.tag, so the user selects the scale (basic, rhythm, suppleness))         switch scaleIndex {         case 0:             currentTraining = \.basicTraining         case 1:             currentTraining = \.rhythm         case 2:             currentTraining = \.suppleness but this doesn't work
Topic: Programming Languages SubTopic: Swift Tags:
Jan ’21