Skip to content

Instantly share code, notes, and snippets.

@Ben-G
Last active October 13, 2016 18:19
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Ben-G/a1196844927577a7b0ca to your computer and use it in GitHub Desktop.
Save Ben-G/a1196844927577a7b0ca to your computer and use it in GitHub Desktop.
Generate Equatable in terms of member fields
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