swift - 在 Swift 中,是否有将数组拆分为前缀和后缀的内置方法?
问题描述
Swift 上是否有一个内置方法Array
将其分成两部分,保留所有元素的顺序?
类似于Array.prefix和Array.suffix
的东西合二为一?
我知道partition
and split
,但它们分别不保留顺序和大小。
例子:
[1,2,3,5,6,2,3,5].cut(where: { $0 < 5 })
>>> ([1,2,3], [5,6,2,3,5])
解决方案
恐怕没有这样的功能,这很遗憾,因为我现在已经多次需要它了。不过,自己动手很容易:
extension RangeReplaceableCollection {
func cut(where belongsInFirstHalf: (Element) -> Bool) -> (SubSequence, SubSequence) {
guard let splittingIndex = self.firstIndex(where: { !belongsInFirstHalf($0) }) else {
return (self[...], SubSequence())
}
return (
self[..<splittingIndex],
self[splittingIndex...]
)
}
}
print([1,2,3,5,6,2,3,5].cut(where: { $0 < 5 })) // => (ArraySlice([1, 2, 3]), ArraySlice([5, 6, 2, 3, 5]))
推荐阅读
- javascript - 显示上的 CSS 过渡:块不起作用
- python - Discord 机器人阅读反应
- ruby-on-rails - 在一个环境中使用 Chewy gem 的 Rails 4 应用程序上的 ElasticSearch Fielddata 错误,但在另一个环境中没有
- spring-cloud-config - Spring Cloud Config - 多个复合存储库?
- python - 如何在 SqlAlchemy orm 中设置主键自动递增
- windows - 带变量的批处理脚本文件传输
- clojure - Compojure Ring 中间件如何在中间件之外使用价值
- git - 分支有提交记录但不存在更改
- javascript - 对 HTTPS 地址的 XMLHTTP POST 请求是否使用任何加密?
- git - 本地仓库中的“remotes/origin/dev”和“origin/dev”有区别吗?