Swift数组元素替换需求:通过for循环替换指定字符串元素
Hey there! Let's get your array replacement logic sorted out. The code you have right now has a couple of issues that are keeping it from working as expected:
self.etype.contains("VALUE ACTIVITY")checks if the entire array has that string, not if the current item in the loop is that string.index(of: "VALUE ACTIVITY")only returns the first occurrence's index, so you can't use it to replace every matching element in the loop.
Option 1: Fix the Existing For Loop
If you want to stick with a for loop to modify the original array in place, here's how to adjust it:
for i in 0..<self.etype.count { let currentItem = self.etype[i] switch currentItem { case "VALUE ACTIVITY": self.etype[i] = "Value" case "BONUS ACTIVITY": self.etype[i] = "Bonus" case "JACKPOT EVENTS": self.etype[i] = "Jackpot" default: // Leave other items unchanged if needed break } }
This loop goes through each index, checks the value at that position, and replaces it with the corresponding shortened string directly in the original array.
Option 2: Use Swift's map (More Idiomatic Approach)
Swift encourages using functional methods like map for this kind of transformation—it's cleaner and avoids manual index management. You can create a new array with the replaced values (and assign it back to etype):
self.etype = self.etype.map { item in switch item { case "VALUE ACTIVITY": return "Value" case "BONUS ACTIVITY": return "Bonus" case "JACKPOT EVENTS": return "Jackpot" default: return item } }
Bonus: Use a Replacement Dictionary for Scalability
If you ever need to add more replacement rules later, using a dictionary to store the mappings makes your code easier to maintain:
// Define your replacement rules in one place let replacementRules: [String: String] = [ "VALUE ACTIVITY": "Value", "BONUS ACTIVITY": "Bonus", "JACKPOT EVENTS": "Jackpot" ] // Apply the replacements with map self.etype = self.etype.map { replacementRules[$0] ?? $0 }
The ?? $0 means "if there's no matching rule for the item, just keep the original value".
内容的提问来源于stack exchange,提问作者gaus

