swift - 在闭包内使用隐式数组值
问题描述
我有一个书籍结构数组Book
,我正在循环尝试查找书籍的属性之一是否等于特定的预定义值,然后我想重新排列元素
if books.contains(where: { $0.structProperty == value }) {
books.rearrange(from: $0, to: 1)
}
这是在数组扩展文件中声明的重新排列函数
extension Array {
mutating func rearrange(from: Int, to: Int) {
insert(remove(at: from), at: to)
}
}
使用此设置,我收到此编译错误:
闭包中不包含匿名闭包参数
我怎样才能在不依赖 for 循环的情况下实现它?
解决方案
contains(where:)
返回一个布尔值,指示数组中是否存在匹配元素,并且
{
books.rearrange(from: $0, to: 1)
}
不是闭包——它是 if 语句中的代码块。
您需要index(where:)
它为您提供第一个匹配元素的位置(或者nil
如果不存在):
if let idx = books.index(where: { $0.structProperty == value }) {
books.rearrange(from: idx, to: 1)
}
另请注意,数组的第一个索引为零,因此如果您打算将数组元素移动到前面,那么它应该是
books.rearrange(from: idx, to: 0)
推荐阅读
- java - 使用 JAXB 解组 XML 返回 NullPointerException
- javascript - 字符串方法需要提示
- python - 如何在重复列表中添加数字
- sql - SQL:很多一对多。缓存?
- java - 如何在材料组件的 dateRangePicker 上使用 setSelection?
- sql - 在数据已经不正确的 postgres 表中添加检查
- ruby-on-rails - Rails 将数据发送到客户端的串口
- javascript - 生成用于测试的网络错误
- python - 使用 ForeignKey 在 Django 中定义属性方法
- html - 为什么表单提交插入“?” 在 URL 的末尾?如何预防?