Skip to content

Instantly share code, notes, and snippets.

@ecmadao
Forked from JohnSundell/AnyOf.swift
Created February 26, 2018 08:51
Show Gist options
  • Save ecmadao/6eab0a784acd1e6668dbfbc8cf6cd1bb to your computer and use it in GitHub Desktop.
Save ecmadao/6eab0a784acd1e6668dbfbc8cf6cd1bb to your computer and use it in GitHub Desktop.
A way to easily compare a given value against an array of candidates
import Foundation
struct EquatableValueSequence<T: Equatable> {
static func ==(lhs: EquatableValueSequence<T>, rhs: T) -> Bool {
return lhs.values.contains(rhs)
}
static func ==(lhs: T, rhs: EquatableValueSequence<T>) -> Bool {
return rhs == lhs
}
fileprivate let values: [T]
}
func any<T: Equatable>(of values: T...) -> EquatableValueSequence<T> {
return EquatableValueSequence(values: values)
}
let string = "Three"
// Instead of multiple conditions like this:
if string == "One" || string == "Two" || string == "Three" {
}
// You can now do:
if string == any(of: "One", "Two", "Three") {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment