Swift - How to get indexes of filtered items of ar

2020-02-05 01:41发布

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

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

Does Swift 3 support a function like whatFunction(_: Element)?

If not, what is the most efficient logic?

8条回答
可以哭但决不认输i
2楼-- · 2020-02-05 02:17

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 
  }

}
查看更多
小情绪 Triste *
3楼-- · 2020-02-05 02:17

You can use that below code:

var firstArray = ["k","d","r","r","p","k","b","p","k","k"]
var secondArray = ["k","d","r","s","d","r","b","c"]

let filterArray = firstArray.filter { secondArray.contains($0) }
let filterArray1 = firstArray.filter { !secondArray.contains($0) }
let filterIndex = firstArray.enumerated().filter { $0.element == "k" }.map { $0.offset }
print(filterArray) --> // ["k", "d", "r", "r", "k", "b", "k", "k"]
print(filterArray1) --> // ["p", "p"]
print(filterIndex) --> // [0, 5, 8, 9]
查看更多
登录 后发表回答