Ios 使用结构作为NSDictionary的键
我正在尝试使用Ios 使用结构作为NSDictionary的键,ios,xcode,cocoa-touch,swift,Ios,Xcode,Cocoa Touch,Swift,我正在尝试使用struct作为NSDictionary中的键。根据文件规定,它必须符合Hashable协议。 我这样做了,但是我得到了一个错误,DateRange不符合协议Hashable和equalable。我怎样才能解决这个问题? 这是我的密码: struct DateRange: Hashable { var startDate: NSDate { return self.startDate.timeIntervalSince1970.hashValue }
struct
作为NSDictionary
中的键。根据文件规定,它必须符合Hashable协议。我这样做了,但是我得到了一个错误,
DateRange
不符合协议Hashable
和equalable
。我怎样才能解决这个问题?这是我的密码:
struct DateRange: Hashable {
var startDate: NSDate {
return self.startDate.timeIntervalSince1970.hashValue
}
var endDate: NSDate {
return self.endDate.timeIntervalSince1970.hashValue
}
}
Hashable
协议有一个必须在结构中实现的属性:
var hashValue: Int { get }
实现可散列协议并不意味着使其属性可散列-必须公开上述属性的是整个结构,其中返回值最好是唯一的,当然这取决于内部状态
请注意,Hashable
协议需要equalable
协议,该协议也必须实现。例如:
struct DateRange: Hashable, Equatable {
var startDate: NSDate
var endDate: NSDate
var hashValue: Int {
return self.startDate.hashValue + 37 * self.endDate.hashValue
}
}
func == (lhs: DateRange, rhs: DateRange) -> Bool {
return lhs.startDate == rhs.startDate && lhs.endDate == rhs.endDate
}
为了计算散列,我使用了
startDate
散列值加上endDate
散列乘以37(一个素数)的总和。此解决方案不考虑溢出,您应该注意防止运行时错误。哈希协议有一个必须在结构中实现的属性:
var hashValue: Int { get }
实现可散列协议并不意味着使其属性可散列-必须公开上述属性的是整个结构,其中返回值最好是唯一的,当然这取决于内部状态
请注意,Hashable
协议需要equalable
协议,该协议也必须实现。例如:
struct DateRange: Hashable, Equatable {
var startDate: NSDate
var endDate: NSDate
var hashValue: Int {
return self.startDate.hashValue + 37 * self.endDate.hashValue
}
}
func == (lhs: DateRange, rhs: DateRange) -> Bool {
return lhs.startDate == rhs.startDate && lhs.endDate == rhs.endDate
}
为了计算散列,我使用了
startDate
散列值加上endDate
散列乘以37(一个素数)的总和。此解决方案不考虑溢出,您应该注意防止运行时错误。除了@Antonio的答案之外,还有一个链接很好地解释了哈希
协议。除了@Antonio的答案,有一个链接很好地解释了Hashable协议。你能写一个工作示例吗?在实现comparator函数时,我遇到了一系列错误,因为我的问题是在类中声明了struct:),但是您的答案非常好!你能写一个有效的例子吗?在实现comparator函数时,我遇到了一系列错误,因为我的问题是在类中声明了struct:),但是您的答案非常好!