Swift 标准库中是否有作用于集合、采用谓词并返回从该集合中移除的值的函数?
目前,我必须分两步实现它:
guard let idx = allAnnotations.index(where: {$0 is MKUserLocation}) else {return}
let userLocation = allAnnotations.remove(at: idx) as! MKUserLocation
但我想,存在类似的功能。
目标
我有以下数组:
[Type1, Type1, Type1, Type1, Type1, Type1, Type2]
Type2
可能存在也可能不存在于数组中。除了这两种,没有其他类型。
我需要把它分成两个元素:
[Type1, Type1, Type1, Type1, Type1, Type1]
和
Type2?
这就是我正在寻找的功能。
最佳答案
Swift 5 有removeAll(where)
@inlinable public mutating func removeAll(where shouldBeRemoved: (Element) throws -> Bool) rethrows
你可以这样使用它-
var array = [1,2,3]
array.removeAll(where: { $0 == 2})
print(array) // [1,3]
关于arrays - 掉落(其中 : {}) remove(where: {}) function in Swift?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50171200/