-
-
Save ianterrell/db082a0efdee5e0df8cc8e744c62a16c 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
//: Playground - noun: a place where people can play | |
import UIKit | |
func generateEquatable(_ t: Any) -> String { | |
var output = "" | |
let mirrorPlace = Mirror(reflecting: t) | |
let type = mirrorPlace.subjectType | |
output += ("extension \(type): Equatable {\n") | |
output += (" static func ==(lhs: \(type), rhs: \(type)) -> Bool {\n") | |
output += (" return ") | |
var lines: [String] = [] | |
for (i, child) in mirrorPlace.children.enumerated() { | |
let ind = (i == 0) ? "" : " " | |
lines.append("\(ind)lhs.\(child.label!) == rhs.\(child.label!)") | |
} | |
output += lines.map{String($0)}.joined(separator: " &&\n") | |
output += ("\n }") | |
output += ("\n}") | |
return output | |
} | |
struct Term { | |
let offset: Int | |
let value: String | |
} | |
let term = Term(offset: 0, value: "") | |
print(generateEquatable(term)) | |
// -> | |
// 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