How to find index of list item in Swift?

后端 未结 22 1588
离开以前
离开以前 2020-11-22 06:17

I am trying to find an item index by searching a list. Does anybody know how to do that?

I see there is list.StartIndex and <

22条回答
  •  有刺的猬
    2020-11-22 06:36

    While indexOf() works perfectly, it only returns one index.

    I was looking for an elegant way to get an array of indexes for elements which satisfy some condition.

    Here is how it can be done:

    Swift 3:

    let array = ["apple", "dog", "log"]
    
    let indexes = array.enumerated().filter {
        $0.element.contains("og")
        }.map{$0.offset}
    
    print(indexes)
    

    Swift 2:

    let array = ["apple", "dog", "log"]
    
    let indexes = array.enumerate().filter {
        $0.element.containsString("og")
        }.map{$0.index}
    
    print(indexes)
    

提交回复
热议问题