How to find index of list item in Swift?

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

    For custom class, you need to implement the Equatable protocol.

    import Foundation
    
    func ==(l: MyClass, r: MyClass) -> Bool {
      return l.id == r.id
    }
    
    class MyClass: Equtable {
        init(id: String) {
            self.msgID = id
        }
    
        let msgID: String
    }
    
    let item = MyClass(3)
    let itemList = [MyClass(1), MyClass(2), item]
    let idx = itemList.indexOf(item)
    
    printl(idx)
    

提交回复
热议问题