我有一个结构 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)
}
}
使用这个设置我得到这个编译错误:
Anonymous closure argument not contained in a closure
如何在不依赖 for 循环的情况下实现它?
最佳答案
contains(where:)
返回一个 bool 值,指示是否匹配
元素是否存在于数组中,并且
{
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)
关于swift - 在闭包中使用隐式数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50435614/