简体   繁体   中英

Swift Array firstIndex & Equatable

I have the following class in Swift

public class ItemModel:Identifiable, Equatable, Loadable {

  public static func == (lhs: ItemModel, rhs: ItemModel) -> Bool {
     return lhs.id == rhs.id
  }

  public var id:UUID

   public init() {
     self.id = UUID()
   }

 }

And then I have subclass

public class SubItemModel:ItemModel {


}

I have an array layerItems of type [SubItemModel]. When I test the following code

    public func removeItem(_ item:SubItemModel) -> Bool {
    
        //This line fails despite $0 and item having same id, why?

        if let index = layerItems.firstIndex(where: {$0 === item}) {
            
            item.cleanup()
            layerItems.remove(at: index)
           
            return true
         }
      }
    
       return false
   }

It returns false because firstIndex(where:...) returns nil. Why is it so despite the item with given id being present in the array?

As vadian notes, === is not the equality operator. It is the "same instance" operator. Two class instances that are "equal" (according to Equatable) will fail === if they are not the same object.

Given your description, you should be able to use firstIndex(of: item) rather than firstIndex(where:) . But also be very careful of implementing == using only a mutable ID. This allows for two objects to have different properties, but still compare "equal" according to Equatable (and therefore interchangeable in all contexts). You generally should not do partial property checking in == for mutable objects or any situation where two objects might differ despite having the same identifer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM