Reputation: 7312
I this is my code, and it is working
if (v1 == v2) && (v2 == v3) {
println("3 strings are equal")
}
Is there any other more Swift way to do it ?
My implementation look like C code :-)
Upvotes: 3
Views: 1045
Reputation: 1365
If you want to be really swifty, you can check an array of strings to be all equal like this (you could wrap that 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 would probably not call it either extremely elegant or super efficient... but it certainly works.
Upvotes: 1
Reputation: 11341
You could do something cool like this:
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 invoke 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
Upvotes: 2
Reputation: 126167
I don't think so. That's about as straightforward as it gets. (And an improvement on C and ObjC, too — you can use the ==
operator instead of calling strcmp
or isEqual:
.)
If you really want to go nuts with it, you might be able to write v1 == v2 == v3
if you created a couple of custom ==
operator overloads. (This is left as an exercise for the reader.) But it's probably not worthwhile.
Upvotes: 4
Reputation: 449
You can use an extension for the string class like this :
extension String {
func allEquals (s1: String, s2: String) {
(this == s1) && (s1 == s2)
}
}
I didn't compiled it but it should work ;)
Upvotes: 1