Everyone should notice that in the do-block (Sample 2). The result is just opposite of the code out of it (Sample 1). Or say, out the do-block, Swift calls `==` directly. In the do-block, Swift just call `isEqual(_)` instead of `==`.
That is the inconsistency I am confused. Zhaoxin On Wed, Apr 19, 2017 at 10:33 AM, Zhao Xin <owe...@gmail.com> wrote: > Sample 1: both `==` and `!=` is true. > > import Foundation > > > class Foo:NSObject { > > let name:String > > > init(name:String) { > > self.name = name > > } > > > public static func ==(lhs: Foo, rhs: Foo) -> Bool { > > guard type(of:lhs) == type(of:rhs) else { return false } > > return lhs.name == rhs.name > > } > > } > > > let a = Foo(name: "bar") > > let b = Foo(name: "bar") > > > print(a == b) // true > > print(a != b) // true > > Sample 2: Add above code to a do-block, behavior changes to expect > > do { > > class Foo:NSObject { > > let name:String > > > > init(name:String) { > > self.name = name > > } > > > > public static func ==(lhs: Foo, rhs: Foo) -> Bool { > > guard type(of:lhs) == type(of:rhs) else { return false } > > return lhs.name == rhs.name > > } > > } > > > > let a = Foo(name: "bar") > > let b = Foo(name: "bar") > > > > print(a == b) // false > > print(a != b) // true > > } > > Sample 3: A little investigation shows that `==` didn't call NSObject's ` > func isEqual(_ object: Any?) -> Bool` but `!=` did. > > class Foo:NSObject { > > let name:String > > > > init(name:String) { > > self.name = name > > } > > > > public static func ==(lhs: Foo, rhs: Foo) -> Bool { > > guard type(of:lhs) == type(of:rhs) else { return false } > > return lhs.name == rhs.name > > } > > > > override func isEqual(to object: Any?) -> Bool { > > print("111") > > return super.isEqual(to: object) > > } > > > > override func isEqual(_ object: Any?) -> Bool { > > print("2222") > > return super.isEqual(object) > > } > > } > > > let a = Foo(name: "bar") > > let b = Foo(name: "bar") > > > print(a == b) // true > > print(a != b) // 2222, true > > print(!(a == b)) // false > > > So I am wondering what is the future? Will we keep on using `isEqual(_ > object: Any?)` with class that inherits `NSObject`, or we are trying to > drop it? > > Xcode 8.3.1 (8E1000a), 3.1 (swiftlang-802.0.51 clang-802.0.41), macOS 10.12.4 > (16E195) > > Zhaoxin >
_______________________________________________ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users