Contains method not working properly and it is giving me false result even if it is matching with Object?
My Code Below
class Generic: NSObject, NSCoding
{
var genericCode: String?
var genericName : String?
var genericType : String?
var genericImageUrl : String?
var genericPhone: String?
var orgName : String?
override init()
{
self.genericCode = String("")
self.genericName = String("")
self.genericType = String("")
self.genericImageUrl = String("")
self.genericPhone = String("")
self.orgName = String("")
}
//Parameterzed Constructor for the Generic
init(genericCode: String , genericName: String , genericPhone: String, genericType: String, genericImageUrl : String)
{
self.genericCode = genericCode
self.genericName = genericName
self.genericType = genericType
self.genericImageUrl = genericImageUrl
self.genericPhone = genericPhone
}
required init(coder aDecoder: NSCoder) {
genericCode = aDecoder.decodeObjectForKey("genericCode") as? String
genericName = aDecoder.decodeObjectForKey("genericName") as? String
genericType = aDecoder.decodeObjectForKey("genericType") as? String
genericPhone = aDecoder.decodeObjectForKey("genericPhone") as? String
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(genericCode, forKey: "genericCode")
aCoder.encodeObject(genericName, forKey: "genericName")
aCoder.encodeObject(genericType, forKey: "genericType")
aCoder.encodeObject(genericPhone, forKey: "genericPhone")
}
}
func ==(lhs: Generic, rhs: Generic) -> Bool
{
return lhs.genericCode == rhs.genericCode
}
Checking in ViewController
print(readArray.contains(generic))
if !readArray.contains(generic)
{
readArray.append(generic)
}
NSObject
– you therefore need to overrideisEqual
to do comparisons. – GratulantString("")
and just""
is exactly the same and be aware of using optional properties and a non-optional initializer. – Belgravia