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

如何从Swift的Shift数组中移除最后一个weekday为Monday的元素?

问题解决

错误原因分析

  1. 你用了firstIndex(where:),它只会返回第一个匹配weekday == "Monday"的元素索引,但你的需求是移除最后一个,方法用错了。
  2. 你调用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 18:34:01