How do I check if 3 strings are equal in Swift?

I this is my code and it works

if (v1 == v2) && (v2 == v3) {
    println("3 strings are equal")
}

      

Is there an even faster way to do this?

My implementation looks like C code :-)

+3


source to share


4 answers


I do not think so. It's as easy as it gets. (And an improvement in C and ObjC too - you can use the operator ==

instead of calling strcmp

or isEqual:

.)



If you really want to go crazy, you can write v1 == v2 == v3

if you've created a couple of custom operator overloads ==

. (This is left as an exercise for the reader.) But it probably isn't worth it.

+4


source


You can do something cool:

extension Array {

    func allEqual(isEqual: (T, T) -> Bool) -> Bool {
        if self.count < 2 {
            return true
        }
        for x in self {
            if !isEqual(x, self.first!) {
                return false
            }
        }
        return true
    }
}

      



And then call it like this:

["X", "Y", "Z"].allEqual(==) // false
["X", "X", "X"].allEqual(==) // true
let one = "1"
var ONE = "1"
var One = "1"
[one, ONE, One].allEqual(==) // true

      

+2


source


You can use a string class extension like this:

extension String {
    func allEquals (s1: String, s2: String) {
        (this == s1) && (s1 == s2)
    }
}

      

I haven't compiled it, but it should work;)

+1


source


If you want to be very careful, you can check for an array of strings equal to it (you can wrap this in an extension, of course):

var array = ["test", "test", "test"]
var allEqual = array.reduce(true, combine: { (accum: Bool, s: String) -> Bool in
    accum && s == array[0]
})

      

I probably wouldn't call it too elegant or super efficient ... but it certainly works.

+1


source







All Articles