Table View开发报错:无法用[String]类型下标访问[String]类型数组
Hey there! Let's break down why you're hitting this error and how to fix it quickly.
The Root Cause
Your indexArray stores string representations of numbers (like "0", "5"), but Swift requires array subscripts to be of type Int. When you try to use textArray[indexArray[row]], you’re passing a String where an Int is needed—this type mismatch is exactly what’s triggering the error.
Solution 1: Use an Int Array for Indexes (Simplest Fix)
If you control the source of indexArray, just define it as an array of integers instead of strings. This eliminates conversion needs entirely:
var indexArray = [0,5,10,15,20] // Now Int type, not String // Added a 21st element to textArray to match index 20 (arrays are zero-indexed) var textArray = ["Tom","Teddy","Mark","John","Samuel","Smith","Chris","Paulo","Simon","Ralf","Mizo","Karim","Lady","Coloy","Samantha","Maro","Kathren","Lyla","Jessika","Amanda","Olivia"]
Then in your cellForRowAt method, you can safely access the value like this:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "YourCellIdentifier", for: indexPath) let targetIndex = indexArray[indexPath.row] cell.textLabel?.text = textArray[targetIndex] return cell }
Solution 2: Safely Convert String Indexes to Int (If You Need to Keep String Array)
If you can’t change indexArray to [Int] (e.g., data comes from an API as strings), use safe conversion to avoid crashes from invalid values:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "YourCellIdentifier", for: indexPath) // Safely convert string to Int, and verify it's a valid index for textArray guard let targetIndex = Int(indexArray[indexPath.row]), targetIndex < textArray.count else { // Handle invalid cases (non-numeric string or out-of-bounds index) cell.textLabel?.text = "N/A" return cell } cell.textLabel?.text = textArray[targetIndex] return cell }
This guard statement ensures two critical things:
- The string can be converted to a valid integer
- The integer is within the bounds of
textArray(no out-of-bounds crashes)
Quick Reminder
Always double-check that your index values don’t exceed the length of textArray. Swift arrays are zero-indexed, so an index of 20 requires textArray to have at least 21 elements.
内容的提问来源于stack exchange,提问作者Samuel

