swift - 在闭包中使用隐式数组值

标签 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)
    }
}

使用这个设置我得到这个编译错误:

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/

相关文章:

swift - hasPrefix 在可选字符串上的行为不当

ios - Xcode App Store 连接操作错误 : Could not find or load main class 12

swift - 检测 UIScrollView 是否具有滚动高度

ios - Swift 泛型类如何从中创建类型对象

swift - 为什么当我点击 UIActivityViewController 上的 "Save Image"选项时我的应用程序崩溃了?

objective-c - stringByReplacingOccurrencesOfString 不起作用?

ios - 按下 tableView 单元格时在不同的 ViewController 中打开 URL

Swift:CoreLocation 如何知道用户允许什么

c - Swift:如何调用从 dylib 加载的 C 函数

ios - textField shouldChangeCharactersInRange 正在执行用户操作后一步