I assume that you want that you have tested someString != niland someString != "a"in a logical expression (rather than the two in and out).
No, I donβt think itβs possible to use the built-in operators, but we will implement the string extension implementation as follows:
extension String {
func isDifferentThan(value: String?) -> Bool {
return value != nil && self != value?
}
}
and you can use the following:
someString = nil
"a".isDifferentThan(someString) // Return false
someString = "b"
"a".isDifferentThan(someString) // Return true
someString = "a"
"a".isDifferentThan(someString) // Return false
Addition . A more elegant solution is to define your own logical operator. I used !~=, but feel free to use your own.
infix operator !~= { associativity left }
func !~= (a: String?, b: String?) -> Bool {
if a == nil || b == nil {
return false
}
return a != b
}
Tested as follows:
someString = nil
someString !~= "a" // Returns false
someString = "b"
someString !~= "a" // Returns true
someString = "a"
someString !~= "a" // Returns false
someString = nil
someString !~= nil // Returns false
nil (, nil, true, , " " true)