【问题标题】:Swift: Convert IndexSet to [IndexPath] [duplicate]Swift:将 IndexSet 转换为 [IndexPath] [重复]
【发布时间】:2020-10-01 08:51:43
【问题描述】:

我想在 Swift 5 中从 IndexSet 获取 [IndexPath]。 在 Objective-C 中有一个question 可以将 NSIndexSet 转换为 Array<NSIndexPath *>。 但是 Swift 5 中没有 enumerateIndexesUsingBlock 方法。 谁知道路?

【问题讨论】:

标签: swift indexpath


【解决方案1】:

在索引上使用map 来创建自定义IndexPath,如下所示:

let customIndexPaths = indexes.map { IndexPath(row: $0, section: 0) }
// Or, You can use the short-form, credits: @Vadian
let customIndexPaths: [IndexPath] = indexes.map { [$0, 0] }

您还可以使用 IndexPath 的初始化程序:

let indexes: IndexSet = [0, 1]
let indexPath = IndexPath(indexes: indexes) // Note: this initializer returns just one indexPath not an array `[IndexPath]`

【讨论】:

  • 第一种形式创建一个 indexPath,而不是数组。
  • 您的最后一个选项indexes.map { [$0, 0] } 没有任何意义。它产生一个二维整数数组。顺便说一句,您可以简单地使用indexes.map(IndexPath.init)
  • @LeoDabus 我忘了说在这种情况下你必须注释类型:let customIndexPaths : [IndexPath] = indexes.map { [$0, 0] }
【解决方案2】:

你可以使用扩展。

extension IndexSet {
    func indexPaths(_ section: Int) -> [IndexPath] {
        return self.map{IndexPath(item: $0, section: section)}
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-15
    • 2016-06-30
    • 2017-01-01
    • 1970-01-01
    • 2014-08-14
    相关资源
    最近更新 更多