How do I check if 3 strings are equal in Swift?
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.
source to share
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
source to share
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.
source to share