Swift - How to get indexes of filtered items of array

后端 未结 9 1139
旧巷少年郎
旧巷少年郎 2020-12-05 18:20
let items: [String] = [\"A\", \"B\", \"A\", \"C\", \"A\", \"D\"]

items.whatFunction(\"A\") // -> [0, 2, 4]
items.whatFunction(\"B\") // -> [1]
相关标签:
9条回答
  • 2020-12-05 18:39

    just copy and paste

    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 
      }
    
    }
    
    0 讨论(0)
  • 2020-12-05 18:44
    /*
    let p_last = [51,42]
    let inds1 = [1,3,51,42,4]
    let idx1 = Array(inds1.filter{ p_last.contains($0) }.indices)
     */
    

    How can we do this to return index [2, 3], that is, elements 51 and 42 in inds1.

    0 讨论(0)
  • 2020-12-05 18:46

    you can use it like that :

     let items: [String] = ["A", "B", "A", "C", "A", "D"]
    
            let indexes = items.enumerated().filter {
                $0.element == "A"
                }.map{$0.offset}
    
            print(indexes)
    
    0 讨论(0)
提交回复
热议问题