How to find index of list item in Swift?

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

    In Swift 4, if you are traversing through your DataModel array, make sure your data model conforms to Equatable Protocol , implement the lhs=rhs method , and only then you can use ".index(of" . For example

    class Photo : Equatable{
        var imageURL: URL?
        init(imageURL: URL){
            self.imageURL = imageURL
        }
    
        static func == (lhs: Photo, rhs: Photo) -> Bool{
            return lhs.imageURL == rhs.imageURL
        }
    }
    

    And then,

    let index = self.photos.index(of: aPhoto)
    

提交回复
热议问题