How to elegantly compare tuples in Swift?

后端 未结 6 1832
眼角桃花
眼角桃花 2020-12-09 08:44

I do have 2 different tuples of type (Double, Double):

let tuple1: (Double, Double) = (1, 2)
let tuple2: (Double, Double) = (3, 4)

I want t

6条回答
  •  感情败类
    2020-12-09 08:53

    Update

    As Martin R states in the comments, tuples with up to six components can now be compared with ==. Tuples with different component counts or different component types are considered to be different types so these cannot be compared, but the code for the simple case I described below is now obsolete.


    Try this:

    func ==  (tuple1:(T,T),tuple2:(T,T)) -> Bool
    {
       return (tuple1.0 == tuple2.0) && (tuple1.1 == tuple2.1)
    }
    

    It's exactly the same as yours, but I called it ==. Then things like:

    (1, 1) == (1, 1)
    

    are true and

    (1, 1) == (1, 2)
    

    are false

提交回复
热议问题