2

I'd like to create an extension off all types that have the .contains API.

For example, I did this for strings, but would like to expand it for all types:

func within(values: [String]) -> Bool {
    return values.contains(self)
}

With this, instead of this:

["abc", "def", "ghi"].contains("def")

I can do this for convenience:

"def".within(["abc", "def", "ghi"])

But I'd like to work with anything like this for example:

[.North, .South].contains(.West)

So I can do this with enums:

let value = .West
value.within([.North, .South])

Is creating a broad extension possible for this scenario?

TruMan1
  • 33,665
  • 59
  • 184
  • 335

1 Answers1

6

That version of the contains method is defined for any SequenceType whose members are Equatable. So what you want is to extend Equatable. Like this:

extension Equatable {
    func within<Seq: SequenceType where Seq.Generator.Element == Self> (values: Seq) -> Bool {
        return values.contains(self)
    }
}
Ole Begemann
  • 135,006
  • 31
  • 278
  • 256
  • 2
    Great answer! I was trying to extend `GeneratorType`, but this is definitely a better approach. – JAL Mar 31 '16 at 13:05