Author Topic: How do I search for my custom objects with Swift's find() and contains() functions?  (Read 10125 times)

kjmcneish

  • Administrator
  • *****
  • Posts: 719
    • View Profile
To use Swift's find() and contains() functions on arrays that contain your custom objects, you need to implement the Equatable protocol in your custom class, structure, or enumeration.

For example, the following code declares a structure named Move that represents a move in a Tic-Tac-Toe game. The position property specifies the location on the Tic-Tac-Toe board and the mark property specifies "X" or "O":

Code: [Select]
public struct Move {
   
    public var position: Position
    public var mark: String
   
    public init(position: Position, mark: String) {
        self.position = position
        self.mark = mark
    }
}

If I have an array of moves:

Code: [Select]
var moves = Array<Move>()
I need to implement the Equatable protocol on the Move structure so I can use Swift's find() and contains() functions on this array. Here's how it's done:

Code: [Select]
public struct Move: Equatable {
   
    public var position: Position
    public var mark: String
   
    public init(position: Position, mark: String) {
        self.position = position
        self.mark = mark
    }
}

public func ==(lhs: Move, rhs: Move) -> Bool {
    return lhs.position == rhs.position && lhs.mark == rhs.mark
}

The Equatable protocol requires the implementation of the == operator at a global scope. That's why the function shown above is declared outside of the Move structure.

It's up to you to specify what equality means for your custom class. In the Move structure, it means the position and mark property values are the same.

Now you can use Swift's find() and contains() functions on this custom structure:

Code: [Select]
let i = find(self.moves, Move(position: .a, mark: "X"))
let doesContain = contains(self.moves, Move(position: .a, mark: "X"))

All the best!
Kevin McNeish
Author of Learn to Code in Swift: https://itunes.apple.com/us/book/learn-to-code-in-swift/id942956811?mt=11