Skip to content

Instantly share code, notes, and snippets.

@chenr2
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chenr2/0f31c677ad85c6beab53 to your computer and use it in GitHub Desktop.
Save chenr2/0f31c677ad85c6beab53 to your computer and use it in GitHub Desktop.
Swift: equatable protocol

How to tell if two things are the same

You want to iterate over an array of custom objects, and need to tell whether two objects are equal. You're not concerned with two objects being identical in memory, but equivalent based on your own definition.

class Student {
    var studentId = 0
    var firstName = "Bob"
}

extension Student : Equatable {}

func ==(lhs: Student, rhs: Student) -> Bool {
    return lhs.studentId == rhs.studentId
}

A few things to note:

  • You conform to the Equatable protocol, but you don't actually implement any methods
  • It's just a function declaration. Instead of this, func foo(){} do this: func ==(){}
  • This equality function is global. Don't put it inside the class.

Now you can iterate over the objects.

if contains(studentArray, studentB) {
    // B is in the Array
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment