Skip to content

Instantly share code, notes, and snippets.

@eMdOS
Created January 11, 2018 01:02
Show Gist options
  • Save eMdOS/0b35327ae9ea20cc85f920b408f8974a to your computer and use it in GitHub Desktop.
Save eMdOS/0b35327ae9ea20cc85f920b408f8974a to your computer and use it in GitHub Desktop.
[Swift] Expressively matching a Value againts a Sequence

Usage:

let string = "one"

// using the global function
if string == any(of: "one", "two", "three") {
    // ..
}

// using the Equatable's extension function
if string.isAny(of: "one", "two", "three") {
    // ..
}
public extension Equatable {
func isAny(of candidates: Self...) -> Bool {
return candidates.contains(self)
}
}
public struct EquatableValueSequence<Value: Equatable> {
private let values: [Value]
public init(values: [Value]) {
self.values = values
}
public static func ==(lhs: EquatableValueSequence<Value>, rhs: Value) -> Bool {
return lhs.values.contains(rhs)
}
public static func ==(lhs: Value, rhs: EquatableValueSequence<Value>) -> Bool {
return rhs == lhs
}
}
public func any<Value: Equatable>(of values: Value...) -> EquatableValueSequence<Value> {
return EquatableValueSequence(values: values)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment