Overloading equivalence (==) operator for custom class in Swift

前端 未结 2 1073
时光说笑
时光说笑 2021-01-07 22:56

Is it possible to overload equivalence (==) operator for a custom class inside that custom class. However I know that it is possible to have this operator overloaded outside

相关标签:
2条回答
  • 2021-01-07 23:38

    No, operators are overloaded using global functions.

    0 讨论(0)
  • 2021-01-07 23:52

    Add global functions. For example:

    class CustomClass {
        var id = "my id"
    }
    
    func ==(lhs: CustomClass, rhs: CustomClass) -> Bool {
        return lhs == rhs
    }
    func !=(lhs: CustomClass, rhs: CustomClass) -> Bool {
        return !(lhs == rhs)
    }
    

    To conform Equatable protocol in Swift 2

    class CustomClass: Equatable {
        var id = "my id"
    }
    
    func ==(left: CustomClass, right: CustomClass) -> Bool {
        return left.id == right.id
    }
    

    To conform Equatable protocol in Swift 3

    class CustomClass {
        var id = "my id"
    }
    
    extension CustomClass: Equatable {
        static func ==(lhs: CustomClass, rhs: CustomClass) -> Bool {
            return lhs.id == rhs.id
        }
    }
    
    0 讨论(0)
提交回复
热议问题