You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中使用removeAll(where:)移除数组元素报错问题排查

解决Swift中removeAll(where:)调用的"Extra argument 'where' in call"错误

这个错误看起来有点误导人——Swift 5确实支持removeAll(where:)方法,问题的根源其实不在方法本身,而在你闭包里的比较逻辑上。

为什么会出现这个错误?

你的CaseFormat是一个类(class),Swift中的类默认没有遵循Equatable协议,所以你直接用$0 == itemToRemove比较两个CaseFormat实例是不合法的。编译器无法解析这个比较表达式,就会错误地认为你调用removeAll时传了多余的参数,从而抛出"Extra argument 'where' in call"的提示。

两种解决方案

方案1:让CaseFormat遵循Equatable协议

如果希望直接用==比较CaseFormat实例,让类遵循Equatable并实现相等判断方法即可。你可以根据业务需求选择用唯一标识(比如id)或者所有属性来判断相等:

class CaseFormat: Equatable {
    var id : Int
    var imageName : String
    var isSelected : Bool
    var solve : String
    var testTicks : Int

    init(id : Int, imageName : String, isSelected : Bool, solve : String, testTicks : Int) {
        self.id = id
        self.imageName = imageName
        self.isSelected = isSelected
        self.solve = solve
        self.testTicks = testTicks
    }

    // 实现Equatable的必要方法
    static func == (lhs: CaseFormat, rhs: CaseFormat) -> Bool {
        // 示例:用id作为唯一判断标准
        return lhs.id == rhs.id
        
        // 如果需要比较所有属性,替换成下面的代码:
        // return lhs.id == rhs.id 
        //    && lhs.imageName == rhs.imageName 
        //    && lhs.isSelected == rhs.isSelected 
        //    && lhs.solve == rhs.solve 
        //    && lhs.testTicks == rhs.testTicks
    }
}

修改后,你原来的removeAll(where:)调用就能正常工作了。

方案2:直接在闭包里用属性判断相等

如果不想修改CaseFormat类,也可以直接在闭包里通过实例的属性(比如id)来判断是否要移除元素:

var itemToRemove = list[indexPath.item]
selectedCasesArray.removeAll(where: { $0.id == itemToRemove.id })

这样编译器能正确解析闭包的逻辑,也就不会再抛出错误提示了。

内容的提问来源于stack exchange,提问作者Luke B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:34:31