• Stars
    star
    125
  • Rank 277,308 (Top 6 %)
  • Language
    Swift
  • License
    MIT License
  • Created over 7 years ago
  • Updated over 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A Swift utility function that generates Equatable protocol code for any object.

Equatable code generator

Suppose you have a struct in your Swift app like this:

struct Person {
    let firstName: String
    let lastName: String
    let birthday: Date
    let inchesTall: Int
}

In order to allow Person instances to be compared for equality, using the == operator, the struct must adopt Swift's Equatable protocol.

// This doesn't work unless Person adopts the Equatable protocol.
let areSamePerson = (person1 == person2)

Writing code to check if two things are the same is boring, so make your computer do it!

// This prints Equatable protocol code for the Person struct.
adoptEquatable(person)

The adoptEquatable function prints this to the console in Xcode…

extension Person: Equatable {
    public static func ==(lhs: Person, rhs: Person) -> Bool {
        guard lhs.firstName == rhs.firstName else { return false }
        guard lhs.lastName == rhs.lastName else { return false }
        guard lhs.birthday == rhs.birthday else { return false }
        guard lhs.inchesTall == rhs.inchesTall else { return false }
        return true
    }
}

Simply copy that code, paste it into your project, and you're done. 🙌

Use it while debugging

Once you've added adoptEquatable to your project you can also call it while debugging, via the po command.

alt tag

That's handy!

Show me the code

Feel free to copy this function into your project and start using it.

import Foundation

// Generates code for a class or struct instance to conform to the Equatable protocol.
public func adoptEquatable(_ subject: Any) {
    let mirror = Mirror(reflecting: subject)
    
    let typeName: String = {
        let fullTypeName = String(reflecting: mirror.subjectType)
        let typeNameParts = fullTypeName.components(separatedBy: ".")
        let hasModulePrefix = typeNameParts.count > 1
        return hasModulePrefix
            ? typeNameParts.dropFirst().joined(separator: ".")
            : fullTypeName
    }()
    
    let propertyNames = mirror.children.map { $0.label ?? "" }
    
    // Associate an indentation level with each snippet of code.
    typealias TemplateGroup = [(Int, String)]
    let templateGroups: [TemplateGroup] = [
        [(0, "extension \(typeName): Equatable {")],
        [(1, "public static func ==(lhs: \(typeName), rhs: \(typeName)) -> Bool {")],
        propertyNames.map { (2, "guard lhs.\($0) == rhs.\($0) else { return false }") },
        [(2, "return true")],
        [(1, "}")],
        [(0, "}")]
    ]
    
    // Apply indentation to each line of code while flattening the list.
    let indent = "    "
    let linesOfCode = templateGroups.flatMap { templateGroup -> [String] in
        return templateGroup.map { (indentLevel: Int, code: String) -> String in
            let indentation = String(repeating: indent, count: indentLevel)
            return "\(indentation)\(code)"
        }
    }
    
    let sourceCode = linesOfCode.joined(separator: "\n")
    print(sourceCode)
}

This repository also includes an Xcode playground if you want to experiment.

More Repositories

1

json2swift

A macOS command line tool that generates excellent Swift data models based on JSON data.
Swift
701
star
2

swift-deep-linking

A simple way to consume custom deep link URLs in a Swift app
Swift
468
star
3

abandoned-strings

Command line program that detects unused resource strings in an iOS or OS X application.
Swift
374
star
4

swift-ascii-art

Swift program that creates ASCII art from an image
Swift
294
star
5

swift-threading

Simplified thread marshaling with a custom Swift operator function
Swift
228
star
6

Wizardry

Reusable way to implement the Wizard UI design in iOS apps
Swift
93
star
7

swift-places

A universal iOS 8 app that makes network calls, written in Swift.
Swift
79
star
8

swift-factory

Shows how to instantiate classes by name in Swift.
Swift
67
star
9

function-composition-in-swift

An interactive introduction to function composition in Swift 3.
Swift
59
star
10

swift-tic-tac-toe

Tic-tac-toe implemented in Swift
Swift
53
star
11

sustainable-coding

A document which describes my ever-evolving perspective on the strive for excellence as a software developer.
51
star
12

reflectable-enum

Shows how to simplify accessing properties in the associated values of Swift enums
Swift
47
star
13

break-a-dollar

Swift code that counts how many ways you can break a dollar
Swift
29
star
14

iOSLogin

This iOS 4 project contains a reusable controller and view for authenticating user credentials. The demo app shows how to replace the default UI with a custom view, which uses the same LoginViewController class.
Objective-C
27
star
15

command-line-calculator

Command line calculator written in Swift.
Swift
26
star
16

iOS-Workflow

A lightweight workflow component for iOS applications.
Objective-C
15
star
17

CustomCellDemo

Shows how to create a custom table view cell using Interface Builder in iOS 4.
Objective-C
11
star
18

Swiftogram

Creating histograms with the Swift language
Swift
10
star
19

Simple-Genetic-Algorithm-in-Objective-C

A "Hello, World!" of genetic algorithms, written in Objective-C.
Objective-C
9
star
20

swift-morse-code

Swift app that converts text to Morse code and plays it out loud
Swift
7
star
21

swift-agent

Thread-safe mutable state in Swift
Swift
6
star
22

elixir_wordsets

Elixir program that uses parallel processing to discover symmetrical word combinations
Elixir
5
star
23

swift-caesar-cipher

A functional implementation of the Caesar cipher in Swift
Swift
5
star
24

dry-munging-kata

Swift implementation of Dave Thomas's DRY Fusion data processing exercise
Swift
4
star
25

transitive-dependencies-kata

Swift implementation of Dave Thomas's Transitive Dependencies programming exercise
Swift
4
star
26

8QueensGeneticAlgorithm

A genetic algorithm written in Objective-C that solves the 8 Queens puzzle.
Objective-C
3
star
27

functional-objc

Reduce, map, and filter methods for NSArray
Objective-C
1
star
28

Auto-Layout-Demo

Shows how to use layout constraints in iOS 6 to center two columns of labels.
Objective-C
1
star