0

我想构建一个可散列值用于我的字典键。它应该由一个包含两个字符串和一个 NSDate 的结构组成。我不确定我hashValue在下面正确构建了我的吸气剂:

// MARK: comparison function for conforming to Equatable protocol
func ==(lhs: ReminderNotificationValue, rhs: ReminderNotificationValue) -> Bool {
    return lhs.hashValue == rhs.hashValue
}
struct ReminderNotificationValue : Hashable {
    var notifiedReminderName: String
    var notifiedCalendarTitle: String
    var notifiedReminderDueDate: NSDate

var hashValue : Int {
    get {
        return notifiedReminderName.hashValue &+ notifiedCalendarTitle.hashValue &+ notifiedReminderDueDate.hashValue
    }
}

init(notifiedReminderName: String, notifiedCalendarTitle: String, notifiedReminderDueDate: NSDate) {
    self.notifiedReminderName = notifiedReminderName
    self.notifiedCalendarTitle = notifiedCalendarTitle
    self.notifiedReminderDueDate = notifiedReminderDueDate
}
}


var notifications: [ReminderNotificationValue : String] = [ : ]

let val1 = ReminderNotificationValue(notifiedReminderName: "name1", notifiedCalendarTitle: "title1", notifiedReminderDueDate: NSDate())
let val2 = ReminderNotificationValue(notifiedReminderName: "name1", notifiedCalendarTitle: "title1", notifiedReminderDueDate: NSDate())

notifications[val1] = "bla1"
notifications[val2] = "bla2"

notifications[val2]   // returns "bla2". 
notifications[val1]   // returns "bla1". But I'd like the dictionary to overwrite the value for this to "bla2" since val1 and val2 should be of equal value.
4

1 回答 1

1

问题不在于您的hashValue实现,而在于==功能。通常,x == y暗示x.hashValue == y.hashValue,但反之则不然 。不同的对象可以有相同的哈希值。甚至

var hashValue : Int { return 1234 }

将是一种无效但有效的哈希方法。

因此,在 中==,您必须比较两个对象是否完全相等:

func ==(lhs: ReminderNotificationValue, rhs: ReminderNotificationValue) -> Bool {
    return lhs.notifiedReminderName == rhs.notifiedReminderName
    && lhs.notifiedCalendarTitle == rhs.notifiedCalendarTitle
    && lhs.notifiedReminderDueDate.compare(rhs.notifiedReminderDueDate) == .OrderedSame
}

NSDate()代码中的另一个问题是创建不同日期的两次调用,作为NSDate绝对时间点,表示为具有亚秒精度的浮点数。

于 2016-06-19T07:54:17.060 回答