How to elegantly compare tuples in Swift?

后端 未结 6 1823
眼角桃花
眼角桃花 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 09:00

    The following approach compares tuple of any number of members of any size, provided they do not contain collection types like Array and Dictionary.

    import Darwin // or Foundation
    /// here we go
    func memeq(var lhs: T, var rhs: T) -> Bool {
        return withUnsafePointers(&lhs, &rhs) {
            memcmp($0, $1, UInt(sizeof(T)))
        } == 0
    }
    
    let l = (false, 42,  log(exp(1.0)))
    let r = (!true, 6*7, exp(log(1.0)))
    println(memeq(l, r))   // expectedly true
    let l2 = (0, [0])
    let r2 = (0, [0])
    println(memeq(l2, r2)) // unfortunately false
    

    Note types are already checked via generics. If they differ, it does not even compile thanks to type checking.

提交回复
热议问题