Skip to content

Instantly share code, notes, and snippets.

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