Swift新手遇Xcode报错:调用时缺少参数标签'at:'
Hey there, let's break down why you're seeing this error and how to fix it quickly for your Swift app.
What's Causing the Error?
The core issue here is that Swift's standard Array type doesn't have a remove(_:) method that accepts an element directly. The remove method you’re trying to use requires you to specify an element’s position with the at: argument label (like remove(at: someIndex)), but you’re passing in the element itself instead of its index in the array.
Solution 1: Find the Element's Index First, Then Remove It
If you’re certain the element exists in your comments or imageFile arrays, you can first locate its index with firstIndex(of:), then delete it safely. We’ll also replace those risky as! force-unwraps with optional binding to avoid crashes:
// Remove the target comment if let targetComment = post["message"] as? String, let commentIndex = self.comments.firstIndex(of: targetComment) { self.comments.remove(at: commentIndex) } // Remove the target image file if let targetFile = post["imageFile"] as? PFFile, let fileIndex = self.imageFile.firstIndex(of: targetFile) { self.imageFile.remove(at: fileIndex) }
Note:
firstIndex(of:)only finds the first occurrence of the element. If your array has duplicates, this method will only delete the first matching entry.
Solution 2: Use filter to Create a New Array Without the Target Element
If you want to delete all instances of the element (or avoid dealing with indexes entirely), use filter to generate a new array that excludes the element you want to remove:
// Remove all matching comments if let commentToRemove = post["message"] as? String { self.comments = self.comments.filter { $0 != commentToRemove } } // Remove all matching image files if let fileToRemove = post["imageFile"] as? PFFile { self.imageFile = self.imageFile.filter { $0 != fileToRemove } }
This approach is safer because it eliminates the risk of index out-of-bounds errors, and it’s cleaner if you need to remove every occurrence of the target element.
Quick Pro Tip: Ditch Force Unwraps!
Your original code uses as!, which will crash your app if post["message"] or post["imageFile"] is missing or the wrong type. Always use as? with optional binding (like in the examples above) to handle these edge cases gracefully.
内容的提问来源于stack exchange,提问作者Daniel.P

