2016-05-23 104 views
4

我在編譯時在Equatable中出現錯誤。 我想在列表中添加find或contains方法來檢查值。 我的代碼下面Swift中的'Generic'對協議'Equatable'的冗餘一致性2.2

class Generic: NSObject, Equatable, NSCoding //Am Having an error - Redundant conformance of 'Generic' to protocol 'Equatable' 

{ 

    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 
} 

錯誤發生,是因爲我使用NSCoding和NSObject的?

+3

'NSObject'已經'Equatable'在Swift2,這樣你就可以刪除協議聲明:http://stackoverflow.com/a/34515270/14955 – Thilo

回答

7

按照docsNSObject符合Equatable

符合
CVarArgType
CustomDebugStringConvertible
CustomStringConvertible
Equatable
哈希的
NSObjectProtocol

...因此,像你的錯誤說,符合Equatable是多餘的...

+1

已刪除錯誤,但沒有與Contains方法檢查?做下面的代碼.... if!readArray.contains(generic) { readArray.append(generic) }我在這裏做了些什麼? –

+0

http://stackoverflow.com/questions/37391580/swift-2-2-contains-method-not-working ...已添加另一個電話 –

0

一個類繼承NSObject已經符合Equatable。所以宣佈Object: Equatable是多餘的。

但是,一致性並不意味着它已被正確實施(NSObject只是檢查指針是否相同)。如果要正確實現EquatableNSObject,只是排除了協議一致性聲明(: Equatable),但仍然實現比較方法:

static func ==(lhs: Object, rhs: Object) -> Bool { 
    return lhs.text == rhs.text 
}