Swift Playground中remove(atOffsets:)编译正常但运行时报类型不匹配错误的原因排查
remove(atOffsets:) Error in Your Swift Code Let's break down why you're hitting this error and how to fix it quickly:
Root Cause
The error candidate expects value of type 'Int' for parameter #1 boils down to one key issue: the remove(atOffsets:) method was added in Swift 5.9. If you're using a Swift version older than 5.9, this method doesn't exist—so the compiler defaults to the closest matching method it can find: remove(at:), which requires a single Int index instead of an IndexSet.
As a side note: you spelled the variable indiciesToRemove (missing a 'd' in the plural of "index"). This isn't causing the current error, but using the standard spelling indicesToRemove will align with Swift's conventions and avoid confusion later.
Solutions
Option 1: Upgrade to Swift 5.9 or newer
If you can update your Swift toolchain (via Xcode updates or a Swift version upgrade), just adjust the variable name (optional but recommended) and your original code will work:
// Correct variable name spelling var indicesToRemove = IndexSet() // ... rest of your existing code ... candies.remove(atOffsets: indicesToRemove) // This works natively in Swift 5.9+
Option 2: Backward-compatible workaround
If you need to support older Swift versions, remove elements by sorting the indices in reverse order first (to avoid index shifting issues) and calling remove(at:) for each index:
// Replace the candies.remove(atOffsets:) line with this block for index in indiciesToRemove.sorted(by: >) { candies.remove(at: index) }
Sorting in reverse order is critical here—removing indices from lowest to highest would shift remaining elements left, making subsequent indices invalid and leading to wrong elements being removed.
Verify the Fix
After applying either solution, your code will correctly filter the candies into the target arrays and remove the matched elements from the original candies array. The final print statement will show the remaining candies as expected.
内容的提问来源于stack exchange,提问作者Paul B

