如何正确更新数组所有元素?汇率数组结合输入金额的实现方案
Hey there! Let's figure out what's going wrong with your code and fix it up, plus show you a cleaner way without manual loops.
First, let's break down why your current loop is causing duplicate entries and incorrect results:
- You're overwriting your original exchange rates: Every time you do
receivedRates = currentAmount, you're replacing your base exchange rate array with the calculated values. That means next time you enter an amount, you're multiplying based on the previous results instead of the original rates—total chaos! - Your loop is iterating over a changing array: Since you modify
receivedRatesinside the loop, each iteration uses the updated (and growing) array, leading to repeated entries being added tocurrentAmount. - Unnecessary Int conversion: Converting the input text to
Intfirst then back toDoublestrips away decimal values (e.g., entering 1.5 becomes 1.0). That's going to throw off your calculations.
Now, let's fix this. First, let's keep your original exchange rates safe—make them a constant so you don't accidentally overwrite them:
// Keep your base rates as a constant so they don't get modified let originalRates: [Double] = [1.1, 1.6, 2.0, 1.3] var currentAmount: [Double] = [] // This will hold your calculated results
Option 1: No manual loop (using map—the Swift way!)
Swift's map function is perfect here—it lets you transform every element in an array with a closure, returning a new array automatically. No need to handle appending or clearing manually:
// First, safely unwrap and convert the input text to a Double guard let inputText = inputTextField.text, let inputAmount = Double(inputText) else { // Handle invalid input (e.g., show an alert to the user) print("Please enter a valid number") return } // Use map to calculate each rate * input amount in one line currentAmount = originalRates.map { rate in rate * inputAmount } // Don't forget to refresh your tableView to show the new data tableView.reloadData()
You can even shorten the map closure to a one-liner if you prefer:
currentAmount = originalRates.map { $0 * inputAmount }
Option 2: Optimized loop (if you still want to use a loop)
If you'd rather stick with a loop, here's how to do it correctly—no more duplicates, no overwriting original rates:
guard let inputText = inputTextField.text, let inputAmount = Double(inputText) else { print("Invalid input") return } // Clear the previous results first to avoid appending to old data currentAmount.removeAll() // Iterate over the ORIGINAL rates, not the changing array for rate in originalRates { let newValue = rate * inputAmount currentAmount.append(newValue) } // Refresh the tableView tableView.reloadData()
The key takeaway here is to always keep your original data (the base exchange rates) intact, and only modify your result array (currentAmount) when you need to update the calculated values.
内容的提问来源于stack exchange,提问作者Ula

