swift Hashable Equatable

本文深入探讨了Swift编程语言中的Hashable和Equatable协议,解释了如何使用这些协议来创建自定义类型,使其能够在集合如Set或Dictionary中正确地进行哈希和比较。文章还详细介绍了哈希值的原理及其与实例相等性的关系。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/// You can use any type that conforms to the `Hashable` protocol in a set or

/// as a dictionary key. Many types in the standard library conform to

/// `Hashable`: Strings, integers, floating-point and Boolean values, and even

/// sets provide a hash value by default. Your own custom types can be

/// hashable as well.

 

public protocol Hashable : Equatable {

 

    public var hashValue: Int { get }

}

 

/// A hash value, provided by a type's `hashValue` property, is an integer that

/// is the same for any two instances that compare equally. That is, for two

/// instances `a` and `b` of the same type, if `a == b`, then

/// `a.hashValue == b.hashValue`. The reverse is not true: Two instances with

/// equal hash values are not necessarily equal to each other.

 

 

 

public protocol Equatable {

    public static func == (lhs: Self, rhs: Self) -> Bool

}

 

extension Equatable {

    public static func != (lhs: Self, rhs: Self) -> Bool

}

 

public func === (lhs: Swift.AnyObject?, rhs: Swift.AnyObject?) -> Bool

public func !== (lhs: Swift.AnyObject?, rhs: Swift.AnyObject?) -> Bool

 

///     let a = IntegerRef(100)

///     let b = IntegerRef(100)

///

///     print(a == a, a == b, separator: ", ")

///     // Prints "true, true"

 

///     class StreetAddress {

///         let number: String

///         let street: String

///         let unit: String?

///

///         init(_ number: String, _ street: String, unit: String? = nil) {

///             self.number = number

///             self.street = street

///             self.unit = unit

///         }

///     }

///     extension StreetAddress: Equatable {

///         static func == (lhs: StreetAddress, rhs: StreetAddress) -> Bool {

///             return

///                 lhs.number == rhs.number &&

///                 lhs.street == rhs.street &&

///                 lhs.unit == rhs.unit

///         }

///     }

 

 

public protocol Comparable : Equatable{

public static func < (lhs: Self, rhs: Self) -> Bool

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值