Created
January 22, 2020 12:53
-
-
Save dotWasim/27a30e916453efbae20b46fc1c6e575a to your computer and use it in GitHub Desktop.
Compare Arrays that implement a common Protocol
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import XCTest | |
protocol Booked { | |
func isEqual(to other: Booked) -> Bool | |
} | |
extension Booked where Self: Equatable{ | |
func isEqual(to other: Booked) -> Bool { | |
if let other = other as? Self{ | |
return self == other | |
} | |
return false | |
} | |
} | |
struct Car: Booked, Equatable { | |
let type: String | |
let serialNumber: String | |
static func == (lhs: Car, rhs: Car) -> Bool { | |
return lhs.type == rhs.type && lhs.serialNumber == rhs.serialNumber | |
} | |
} | |
struct Appartement: Booked, Equatable { | |
let name: String | |
let location: String | |
static func == (lhs: Appartement, rhs: Appartement) -> Bool { | |
return lhs.name == rhs.name && lhs.location == rhs.location | |
} | |
} | |
struct UserBookings: Equatable { | |
var bookings: [Booked] | |
static func == (lhs: UserBookings, rhs: UserBookings) -> Bool {tr | |
if lhs.bookings.count == rhs.bookings.count { | |
return !zip(lhs.bookings, rhs.bookings).contains(where: { !$0.isEqual(to: $1) }) | |
} | |
return false | |
} | |
} | |
//MARK: - TEST | |
let car1 = Car(type: "X Model", serialNumber: "abc") | |
let car2 = Car(type: "Y Model", serialNumber: "123") | |
let appartment1 = Appartement(name: "X Hotel", location: "Palestine") | |
let appartment2 = Appartement(name: "Y Hotel", location: "Turkey") | |
let list1 = UserBookings(bookings: [car1, car2, appartment1]) | |
let list2 = UserBookings(bookings: [car1, car2, appartment1]) | |
let differentList = UserBookings(bookings: [car1, car2, appartment1, appartment2]) | |
XCTAssert(list1 == list2, "list1 Equals list2") | |
XCTAssert(list1 != differentList, "Not equal") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment