swift - 使用 reduce 将结构的属性附加到数组

标签 swift

我有一个项目数组

struct Item {
    var id: String
}

如何使用 reduce 函数将所有 ID 附加到数组?

我的尝试:

self.items.reduce([String](), { $0.0.append($0.1.id)})

但是编译器显示错误:

Contextual closure type '(_, [Item]) -> _' expects 2 arguments, but 1 was used in closure body

最佳答案

试试这个:

items.reduce([String](), { res, item in
    var arr = res
    arr.append(item.id)
    return arr
})

关于swift - 使用 reduce 将结构的属性附加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45463941/

相关文章:

ios - 使用 RxSwift 处理请求时出错

ios - 关闭 FSCalendar 中过去的日期

ios - 使用 Facebook SDK 4.1 快速获取 Facebook 相册数组

ios - 在 Swift 中以编程方式创建 UITableViewCell

ios - TextContainer 在更改 UITextView 的边界时不调整大小

swift - 用于在 UICollectionView 中下载和显示图像的 UIImageView 扩展

ios - 上下文类型 'Void' (又名 '()' )不能与数组文字一起使用

ios - 我无法为 UICollectionViewCell 子类或其任何 subview 设置动画

json - 类型 any 没有下标成员 swift 3

ios - SwiftUI:带有可选内部 View 的 View