swift set intersect,union,subtract

时间:2016-03-20 23:57:20

标签: swift set

有没有人知道如何使用用户定义的类实现set操作,其属性为操作条件。例如:

class myClass {
  var figure: Int!
} 

let classObj1 = myClass() 
classObj1.figure = 1

let classObj2 = myClass()
classObj2.figure = 2

let classObj3 = myClass()
classObj3.figure = 1

let set1: Set = [classObj1]
let set2: Set = [classObj2, classObj3]

是否有类似的方法:(伪代码)

set2.substract(set1) {s2, s1 in s2.figure == s1.figure}

...所以预期的结果是[classObj2]

非常感谢任何建议!

1 个答案:

答案 0 :(得分:1)

当然可以。以==比较figure值的方式使MyClass符合Hashable和Equatable。例如:

class MyClass : Hashable {
    var figure: Int
    init(f:Int) {figure = f}
    var hashValue : Int {return figure}
}
func ==(lhs:MyClass, rhs:MyClass) -> Bool {
    return lhs.figure == rhs.figure
}