首页 > 解决方案 > 在闭包内使用隐式数组值

问题描述

我有一个书籍结构数组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 循环的情况下实现它?

标签: swift

解决方案


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)

推荐阅读