Recently I saw an interesting interview question on the Internet. Is it possible for the expression a == 1&& a == 2&& a == 3 to be true in JavaScript? The author gives several answers in JavaScript.

So I thought, how do I make this expression true in Swift?

If you want to add a value to an object, then add one to the value of the object when you compare it

class Number  {
    var value: Int
    init(value: Int) {
        self.value = value
    }
}

func == (lhs: Number, rhs: Int) -> Bool {
    let leftValue = lhs.value
    lhs.value += 1
    return leftValue == rhs
}

let a = Number(value: 1)
print(a == 1 && a == 2 && a == 3)
Copy the code

This method can also be used without custom objects, or through Pointers, as shown below

func == (lhs: UnsafeMutablePointer<Int>, rhs: Int) -> Bool { let leftValue = lhs.pointee lhs.pointee = lhs.pointee + 1 return ! (leftValue ! = rhs) } var b = 1 var a = withUnsafeMutablePointer(to: &b) { $0 } print(a == 1 && a == 2 && a == 3)Copy the code

Idea 2: using ExpressibleByIntegerLiteral Equatable ExpressibleByIntegerLiteral: two protocols can make a custom class initialized by literal Equatable: You can compare your custom classes with == and with these two protocols, you can take the a==1 comparison into the method that implements the Equatable protocol, and then handle it logically in that method as follows

class Number : ExpressibleByIntegerLiteral, Equatable {
    var value: Int
    required init(integerLiteral value: Int) {
        self.value = value
    }
    
    static func == (lhs: Number, rhs: Number) -> Bool {
        let leftValue = lhs.value
        lhs.value += 1
        return leftValue == rhs.value
    }
}

let a = Number(integerLiteral: 1)
print(a == 1 && a == 2 && a == 3)
Copy the code