Protocols - Equatable

public protocol Equatable {

    /// Returns a Boolean value indicating whether two values are equal.
    ///
    /// Equality is the inverse of inequality. For any values `a` and `b`,
    /// `a == b` implies that `a != b` is `false`.
    ///
    /// - Parameters:
    ///   - lhs: A value to compare.
    ///   - rhs: Another value to compare.
    static func == (lhs: Self, rhs: Self) -> Bool
}

协议仅有一个 static 的方法 ==
用来判断两个 数据 是否相等。
类似于OC的 isEqualTo: 方法。

举例:

struct Animation {
    
    var name: String
    var age: Int
}

extension Animation: Equatable {
    
    static func ==(lhs: Self, rhs: Self) -> Bool {
        return lhs.name == rhs.name
    }
}

let dogA = Animation(name: "dog", age: 1)
let dogB = Animation(name: "dog", age: 2)

print(dogA == dogB)

输出:

true

你可能感兴趣的:(Protocols - Equatable)