Skip to content

Instantly share code, notes, and snippets.

@JohnSundell
Created August 21, 2017 21:23
Show Gist options
  • Star 38 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save JohnSundell/1956ce36b9303eb4bf912da0de9e2844 to your computer and use it in GitHub Desktop.
Save JohnSundell/1956ce36b9303eb4bf912da0de9e2844 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") {
}
@AliSoftware
Copy link

AliSoftware commented Aug 21, 2017

Can I play, please please please, can I, please please? 😆

infix operator 
func  <T: Equatable>(lhs: T, rhs: [T]) -> Bool {
  return rhs.contains(lhs)
}

2  [1,2,3] // true
string  ["One", "Two", "Three"]

@tobatha
Copy link

tobatha commented Aug 29, 2017

lol, dope! love the ∈

@matt-curtis
Copy link

But... but... why not just ['One', 'Two', 'Three'].contains('One')?

@adamzbl
Copy link

adamzbl commented Aug 14, 2018

@matt-curtis hahahahahaha.

@guzhenhuaGitHub
Copy link

guzhenhuaGitHub commented Aug 23, 2018

The ∈ is really nice. But I guess I can only use it with the clipboard

@LuDamon
Copy link

LuDamon commented Nov 16, 2021

真是脱裤子放屁——多此一举

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment