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

Swift标准库中是否有接收谓词、移除并返回元素的drop/remove类函数?

Swift集合:移除并返回符合谓词的元素

嘿,这个问题问得很实用!其实Swift标准库本身没有直接提供一个同时移除并返回第一个符合谓词条件元素的现成方法,但我们可以通过扩展集合协议轻松实现这个需求,比你现在的两步写法更简洁~

针对你的场景的解决方案

你的需求是找到并移除数组中唯一可能存在的MKUserLocation类型元素,我们可以给RangeReplaceableCollection(Array遵循这个协议)扩展一个removeFirst(where:)方法:

extension MutableCollection where Self: RangeReplaceableCollection {
    mutating func removeFirst(where predicate: (Element) throws -> Bool) rethrows -> Element? {
        guard let index = try index(where: predicate) else {
            return nil
        }
        return remove(at: index)
    }
}

这样你原来的两步代码就可以简化成一行:

if let userLocation = allAnnotations.removeFirst(where: { $0 is MKUserLocation }) as? MKUserLocation {
    // 处理找到的用户位置
} else {
    // 未找到MKUserLocation的情况
}

额外补充:移除所有符合条件的元素并返回

如果之后你有需要移除所有符合条件的元素并返回它们的需求,也可以扩展一个类似的方法:

extension RangeReplaceableCollection {
    mutating func extractAll(where predicate: (Element) throws -> Bool) rethrows -> [Element] {
        let extractedElements = try filter(predicate)
        try removeAll(where: predicate)
        return extractedElements
    }
}

使用示例:

// 移除数组中所有Type2类型的元素并返回
let type2Elements = array.extractAll(where: { $0 is Type2 })

内容的提问来源于stack exchange,提问作者Richard Topchii

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:58:59