Last active
October 13, 2016 18:19
-
-
Save Ben-G/a1196844927577a7b0ca to your computer and use it in GitHub Desktop.
Generate Equatable in terms of member fields
This file contains hidden or 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 | |
struct Term { | |
let offset: Int | |
let value: String | |
} | |
let term = Term(offset: 0, value: "") | |
let output = generateEquatable(term) | |
print(output) | |
func generateEquatable(t: Any, indentation ind: String = "\t") -> String { | |
var output = "" | |
let mirrorPlace = Mirror(reflecting: t) | |
let type = mirrorPlace.subjectType | |
output += ("extension \(type): Equatable {} \n\n") | |
output += ("func ==(lhs: \(type), rhs: \(type)) -> Bool {\n") | |
output += ("\(ind)return\n") | |
var lines: [String] = [] | |
for child in mirrorPlace.children { | |
lines.append("\(ind)\(ind)lhs.\(child.label!) == rhs.\(child.label!)") | |
} | |
output += " &&\n".join(lines) | |
output += ("\n}") | |
return output | |
} | |
/* | |
Example Output: | |
extension Term: Equatable {} | |
func ==(lhs: Term, rhs: Term) -> Bool { | |
return | |
lhs.offset == rhs.offset && | |
lhs.value == rhs.value | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment