【发布时间】:2017-09-05 15:39:33
【问题描述】:
我正在尝试使用自定义对象创建一个 Set。 这是有效的,如果我使用一组我的自定义对象,则没有重复:
public class AttributesGroup: Hashable, Equatable, Comparable {
open var id: Int!
open var name: String!
open var position: Int!
public init (id: Int = 0, name: String = "", position: Int = 0) {
self.id = id
self.name = name
self.position = position
}
open var hashValue: Int {
get {
return id.hashValue
}
}
public static func ==(lhs: AttributesGroup, rhs: AttributesGroup) -> Bool {
return lhs.id == rhs.id
}
public static func < (lhs: AttributesGroup, rhs:AttributesGroup) -> Bool {
return lhs.position < rhs.position
}
}
我用 NSObject 扩展了我的类,因为 NSObject 已经实现了 Hashable 协议(以及 Equatable)我必须重写 hashValue,这不再起作用,如果我使用一组我的自定义对象有重复,我该怎么办这里做错了吗? :
public class AttributesGroup: NSObject, Comparable {
open var id: Int!
open var name: String!
open var position: Int!
public init (id: Int = 0, name: String = "", position: Int = 0) {
self.id = id
self.name = name
self.position = position
}
open override var hashValue: Int {
get {
return id.hashValue
}
}
public static func ==(lhs: AttributesGroup, rhs: AttributesGroup) -> Bool {
return lhs.id == rhs.id
}
public static func < (lhs: AttributesGroup, rhs:AttributesGroup) -> Bool {
return lhs.position < rhs.position
}
}
感谢您的帮助!
【问题讨论】:
-
与往常一样,从不将属性声明为隐式展开的可选项,这些选项在
init方法中使用非可选值初始化。不幸的是,许多 horrible 教程都提出了这种 horrible 的习惯。不要那样做,永远不要。去掉感叹号。 -
@vadian 你说得对,这是个坏习惯。谢谢。
-
@Hamish 很有趣,我现在明白了,谢谢
标签: swift3 set hashable equatable