如何从Swift的Shift数组中移除最后一个weekday为Monday的元素?
问题解决
错误原因分析
- 你用了
firstIndex(where:),它只会返回第一个匹配weekday == "Monday"的元素索引,但你的需求是移除最后一个,方法用错了。 - 你调用
index.removeLast()是完全错误的——index是Int类型的数组索引值,它根本没有removeLast方法,删除元素的操作应该作用在shifts数组本身。
正确代码实现
要移除数组中最后一个weekday为"Monday"的元素,应该用lastIndex(where:)获取目标索引,再调用数组的remove(at:)方法:
if let lastMondayIndex = shifts.lastIndex(where: { $0.weekday == "Monday" }) { shifts.remove(at: lastMondayIndex) }
补充说明
lastIndex(where:)会从数组末尾往前查找,返回第一个(也就是原数组中最后一个)符合条件的元素索引- 数组的
remove(at:)方法才是根据指定索引删除元素的正确方式,而removeLast()是直接删除数组最后一个元素,不需要传索引
内容的提问来源于stack exchange,提问作者devOP1
相关产品推荐
相关产品推荐

