Home > Software design >  Is there really no in() comparison operator for Swift?
Is there really no in() comparison operator for Swift?

Time:03-23

Starting to code in Swift. Previous experience with other languages. I am looking for an in() comparison for if statements as I have a list of values I want to compare to. In other languages I would do something like this:

if x in("this", "that", "other") then...

However, I have Googled and Googled and it Swift doesn't seem to have such basic functionality. Is this really true? (or is Google just so optimized for ads nowadays the question is getting left behind) Do I really need to:

if x == "this" || x = "that" || or x = "other"

I wrote this String extension using array.contains() to handle this (which works but in my mind is backwards), but I cannot believe I am the first user to want this and I would rather not hack my way through this.

extension String {
    
    func inArr(_ list:[String]) -> Bool {
        
        return list.contains(self)
        
    }
    
}

CodePudding user response:

Use an array:

        if ["this", "that", "other"].contains("that") {
            print("Yes, it's in")
        }

CodePudding user response:

Not a direct answer to your question but you can create a custom operator to accomplish something similar to what you want:

extension Sequence where Element: Equatable {
    static func ~=(lhs: Element, rhs: Self) -> Bool {
        rhs.contains(lhs)
    }
}

Usage:

if "that" ~= ["this", "that", "other"] {
    print(true)  // true
}
  • Related