Swift - 如何获取数组的过滤项的索引

时间:2017-08-29 07:27:02

标签: arrays swift swift3 swift4

let items: [String] = ["A", "B", "A", "C", "A", "D"]

items.whatFunction("A") // -> [0, 2, 4]
items.whatFunction("B") // -> [1]

Swift 3是否支持像whatFunction(_: Element)这样的功能?

如果没有,最有效的逻辑是什么?

10 个答案:

答案 0 :(得分:17)

您可以直接过滤数组的indices,避免额外的map ping。

let items = ["A", "B", "A", "C", "A", "D"]
let filteredIndices = items.indices.filter {items[$0] == "A"}

Array扩展程序:

extension Array where Element: Equatable {

    func whatFunction(_ value :  Element) -> [Int] {
        return self.indices.filter {self[$0] == value}
    }

}

items.whatFunction("A") // -> [0, 2, 4]
items.whatFunction("B") // -> [1]

或更通用的

extension Collection where Element: Equatable {

    func whatFunction(_ value :  Element) -> [Index] {
        return self.indices.filter {self[$0] == value}
    }

}

答案 1 :(得分:12)

您可以为数组创建自己的扩展程序。

:)

您可以像这样简单地调用它

#!/bin/sh
dllVersion=$(powershell.exe '[System.Diagnostics.FileVersionInfo]::GetVersionInfo("YourDll.dll").FileVersion')

答案 2 :(得分:9)

您可以通过以下链条实现此目标:

  1. enumerated() - 添加索引;
  2. filter()不必要的项目;
  3. map()我们的索引。
  4. 示例(适用于 Swift 3 - Swift 4.x ):

    let items: [String] = ["A", "B", "A", "C", "A", "D"]  
    print(items.enumerated().filter({ $0.element == "A" }).map({ $0.offset })) // -> [0, 2, 4]
    

    另一种方法是使用flatMap,它允许你在一个闭包中检查元素并返回索引。

    示例(适用于 Swift 3 - Swift 4.0 ):

    print(items.enumerated().flatMap { $0.element == "A" ? $0.offset : nil }) // -> [0, 2, 4]
    

    但是,由于可以返回非零对象的Swift 4.1 flatMap已被弃用,而是应该使用compactMap

    示例(自 Swift 4.1 起作用):

    print(items.enumerated().compactMap { $0.element == "A" ? $0.offset : nil }) // -> [0, 2, 4]
    

    最干净,最便宜的方法是迭代数组indices并检查当前索引处的数组元素是否等于所需元素。

    示例(适用于 Swift 3 - Swift 4.x ):

    print(items.indices.filter({ items[$0] == "A" })) // -> [0, 2, 4]
    

答案 3 :(得分:8)

Swift 3 Swift 4 中,您可以这样做:

let items: [String] = ["A", "B", "A", "C", "A", "D"]

extension Array where Element: Equatable {

    func indexes(of item: Element) -> [Int]  {
        return enumerated().compactMap { $0.element == item ? $0.offset : nil }
    }
}

items.indexes(of: "A")

我希望我的回答很有帮助

答案 4 :(得分:2)

你可以这样使用它:

 let items: [String] = ["A", "B", "A", "C", "A", "D"]

        let indexes = items.enumerated().filter {
            $0.element == "A"
            }.map{$0.offset}

        print(indexes)

答案 5 :(得分:1)

只需复制并粘贴

extension Array {
  func whatFunction(_ ids :  String) -> [Int] {

    var mutableArr = [Int]()
    for i in 0..<self.count {
        if ((self[i] as! String) == ids) {
            mutableArr.append(i)
        }
    }
        return mutableArr 
  }

}

答案 6 :(得分:1)

您可以在下面的代码中使用它:

NSInteger i = 1;
NSInteger j = 2;

NSInteger ij = i * 1000 + j;

switch (ij) {
    case 1001:
        [self functionNormal];
        break;

    case 1002:
        [self functionUncommon];
        break;

    case 1003:
        [self functionRare];
        break;

    case 2001:
        [self secondFunctionNormal];
        break;

    case 2002:
        [self secondFunctionUncommon];
        break;

    case 2003:
        [self secondFunctionRare];
        break;

    default:
        NSLog(@"case was something else: %ld", (long)ij);
        break;
}

答案 7 :(得分:0)

例如查找inds1数组中的p_last值的索引:(swift 4 +)

let p_last = [51,42]
let inds1 = [1,3,51,42,4]
let idx1 = Array(inds1.filter{ p_last.contains($0) }.indices)

idx1 = [0,1]

答案 8 :(得分:0)

/*
let p_last = [51,42]
let inds1 = [1,3,51,42,4]
let idx1 = Array(inds1.filter{ p_last.contains($0) }.indices)
 */

如何执行此操作以返回索引[2,3],即inds1中的元素51和42。

答案 9 :(得分:0)

这也是一种方式

// MARK: - ZIP: Dictionary like

let words = ["One", "Two", "Three", "Four"]
let numbers = 1...words.count

for (word, number) in zip(words, numbers) {
    print("\n\(word): \(number)")
}