How to find index of list item in Swift?

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

    Swift 5

    func firstIndex(of element: Element) -> Int?
    
    var alphabets = ["A", "B", "E", "D"]
    

    Example1

    let index = alphabets.firstIndex(where: {$0 == "A"})
    

    Example2

    if let i = alphabets.firstIndex(of: "E") {
        alphabets[i] = "C" // i is the index
    }
    print(alphabets)
    // Prints "["A", "B", "C", "D"]"
    

提交回复
热议问题