Swift 2.0在包含NSObject子类时设置不正常

muv*_*aaa 7 set nsobject swift swift2

将我们的代码库升级到Swift2后,我遇到了异常的问题.Set不是预期的减法或联合.

class A: NSObject {
    let h: Int

    init(h: Int) {
        self.h = h
    }

    override var hashValue: Int {
        return h
    }
}

func ==(lhs: A, rhs: A) -> Bool {
    return lhs.hashValue == rhs.hashValue
}

let a = A(h: 1)
let b = A(h: 1)

var sa = Set([a])
let sb = Set([b])

sa.subtract(sb).count // Swift1.2 prints 0, Swift 2 prints 1

sa.contains(a) // Swift1.2 true, Swift 2 true
sa.contains(b) // Swift1.2 true, Swift 2 false
Run Code Online (Sandbox Code Playgroud)

看起来新的Set没有使用hashValue进行内部操作.任何想法是一个错误,或解决这个问题的方法?

小智 12

我玩了你的代码了一下.我能够通过不再继承NSObject来使其工作,而是符合Hashable协议:

class A: Hashable {
    let h: Int

    init(h: Int) {
        self.h = h
    }

    var hashValue: Int {
        return h
    }

}

func ==(lhs: A, rhs: A) -> Bool {
    return lhs.hashValue == rhs.hashValue
}

let a = A(h: 1)
let b = A(h: 1)

var sa = Set([a])
let sb = Set([b])

sa.subtract(sb).count // Swift1.2 prints 0, Swift 2 prints 1

sa.contains(a) // Swift1.2 true, Swift 2 true
sa.contains(b) // Swift1.2 true, Swift 2 false

a.hashValue == b.hashValue
Run Code Online (Sandbox Code Playgroud)

当您从NSObject继承时,您的==重载实际上并未执行.如果你想让它与NSObject一起使用,你必须覆盖isEquals:

override func isEqual(object: AnyObject?) -> Bool {
    if let object = object as? A {
        return object.h == self.h
    } else  {
        return false
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 在Swift 3中使用NSObject正确设置Set似乎需要isEqual和hashValue (2认同)