Created
November 12, 2015 04:49
-
-
Save gravicle/e7725e8099a38bb205f8 to your computer and use it in GitHub Desktop.
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
//: Playground - noun: a place where people can play | |
import Foundation | |
protocol Compatible { | |
func equal(rhs: Compatible) -> Bool | |
} | |
extension String: Compatible { | |
func equal(rhs: Compatible) -> Bool { | |
guard let rhs = rhs as? String else { | |
return false | |
} | |
return self == rhs | |
} | |
} | |
extension Float: Compatible { | |
func equal(rhs: Compatible) -> Bool { | |
guard let rhs = rhs as? Float else { | |
return false | |
} | |
return self == rhs | |
} | |
} | |
extension Int: Compatible { | |
func equal(rhs: Compatible) -> Bool { | |
guard let rhs = rhs as? Int else { | |
return false | |
} | |
return self == rhs | |
} | |
} | |
extension Bool: Compatible { | |
func equal(rhs: Compatible) -> Bool { | |
guard let rhs = rhs as? Bool else { | |
return false | |
} | |
return self == rhs | |
} | |
} | |
extension Double: Compatible { | |
func equal(rhs: Compatible) -> Bool { | |
guard let rhs = rhs as? Double else { | |
return false | |
} | |
return self == rhs | |
} | |
} | |
struct CustomType { | |
var someNumber = 11 | |
} | |
struct Person { | |
var name = "John Nash" | |
var age = 42 | |
var isOld = false | |
var height = 5.11 | |
var floatability: Float = 0.12 | |
var customType = CustomType() | |
} | |
let person0 = Person() | |
var person1 = Person() | |
func areEqual<T>(lhs lhs: T, rhs: T) -> Bool { | |
let leftKeyValues = Mirror(reflecting: lhs).children | |
let rightKeyValues = Mirror(reflecting: rhs).children | |
var leftKeys = [String]() | |
leftKeyValues.forEach { (key, _) -> () in | |
guard let key = key else { return } | |
leftKeys.append(key) | |
} | |
var rightKeys = [String]() | |
rightKeyValues.forEach { (key, _) -> () in | |
guard let key = key else { return } | |
rightKeys.append(key) | |
} | |
guard leftKeys == rightKeys else { return false } | |
for (lKey, lValue) in leftKeyValues { | |
for (rKey, rValue) in rightKeyValues { | |
if lKey == rKey { | |
if let lPrimitive = lValue as? Compatible, | |
rPrimitive = rValue as? Compatible { | |
if !lPrimitive.equal(rPrimitive) { | |
return false | |
} | |
} else { | |
if !areEqual(lhs: lValue, rhs: rValue) { | |
return false | |
} | |
} | |
} | |
} | |
} | |
return true | |
} | |
areEqual(lhs:person0, rhs:person1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment