Created
November 13, 2015 00:23
-
-
Save mpurland/134ef557dfe92acba9e1 to your computer and use it in GitHub Desktop.
Swift classes extending NSObject overriding ==
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The following shows that Equatable for NSObject is not necessarily safe | |
// for Swift classes that extend NSObject and override Equatable. | |
// Reference: http://natashatherobot.com/swift-equatable-with-optionals/ | |
class TitleNSObject: NSObject { | |
var title: String = "" | |
init(title: String) { | |
super.init() | |
self.title = title | |
} | |
} | |
// NSObject is already declared to be Equatable | |
//extension Title: Equatable {} | |
func ==(lhs: TitleNSObject, rhs: TitleNSObject) -> Bool { | |
return lhs.title == rhs.title | |
} | |
let t = TitleNSObject(title: "a") | |
let tOptional: TitleNSObject? = TitleNSObject(title: "a") | |
t == tOptional // false | |
tOptional == t // false | |
t == tOptional! // true | |
tOptional! == t // true | |
struct Title { | |
let title: String | |
} | |
extension Title: Equatable {} | |
func == (lhs: Title, rhs: Title) -> Bool { | |
return lhs.title == rhs.title | |
} | |
let t2 = Title(title: "a") | |
let t2Optional: Title? = Title(title: "a") | |
t2 == t2Optional // true | |
t2Optional == t2 // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment