How to find index of list item in Swift?

后端 未结 22 1597
离开以前
离开以前 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:53

    You can filter an array with a closure:

    var myList = [1, 2, 3, 4]
    var filtered = myList.filter { $0 == 3 }  // <= returns [3]
    

    And you can count an array:

    filtered.count // <= returns 1
    

    So you can determine if an array includes your element by combining these:

    myList.filter { $0 == 3 }.count > 0  // <= returns true if the array includes 3
    

    If you want to find the position, I don't see fancy way, but you can certainly do it like this:

    var found: Int?  // <= will hold the index if it was found, or else will be nil
    for i in (0..x.count) {
        if x[i] == 3 {
            found = i
        }
    }
    

    EDIT

    While we're at it, for a fun exercise let's extend Array to have a find method:

    extension Array {
        func find(includedElement: T -> Bool) -> Int? {
            for (idx, element) in enumerate(self) {
                if includedElement(element) {
                    return idx
                }
            }
            return nil
        }
    }
    

    Now we can do this:

    myList.find { $0 == 3 }
    // returns the index position of 3 or nil if not found
    

提交回复
热议问题