这太疯狂了。我正在比较两个自定义类型的数组,但它表示不相等,但实际上是相等的,因为我在其中打印了所有对象,并用https://www.diffchecker.com
检查了它们是否不同,是否相同!我正在使用Swift 4.2
func deleteFavorite(_ favorite: Favorite) {
var oldFavorites = getFavoriteSurahs()
oldFavorites.forEach {
$0.reciter.surahs.forEach {
print($0.name)
print($0.number)
}
print()
favorite.reciter.surahs.forEach {
print($0.name)
print($0.number)
}
print(NSArray(array:
$0.reciter.surahs).isEqual(favorite.reciter.surahs))
// It prints false BUT IT SHOULD PRINT TRUE, BECAUSE THEY'RE ACTUALLY EQUAL
}
}
那是我的《古兰经》课:
class Surah: NSObject, NSCoding {
private(set) public var name: String
private(set) public var number: Int
init(number: Int, name: String) {
self.number = number
self.name = name
}
func encode(with aCoder: NSCoder) {
aCoder.encode(self.name, forKey: "name")
aCoder.encode(self.number, forKey: "number")
}
required init?(coder aDecoder: NSCoder) {
self.name = aDecoder.decodeObject(forKey: "name") as! String
self.number = aDecoder.decodeInteger(forKey: "number")
}
}
这是我的getFavoriteSurahs()
函数:
func getFavoriteSurahs() -> [Favorite] {
if let favoritesData = self.object(forKey: UD_FAVORITES) as? Data {
do {
let favorites = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(favoritesData) as! [Favorite]
return favorites
} catch {
debugPrint(error)
return [Favorite]()
}
} else {
print("EMPTY Favorites")
return [Favorite]()
}
}
更新 这是如此转储:
print($0.surah.number == favorite.surah.number)
print($0.surah.name == favorite.surah.name)
// Prints true
print($0.surah == favorite.surah)
// Prints false
更新2
if $0.reciter.name == favorite.reciter.name && $0.reciter.image == favorite.reciter.image && $0.reciter.documentID == favorite.reciter.documentID &&
$0.reciter.surahs.count == favorite.reciter.surahs.count &&
$0.surah.number == favorite.surah.number &&
$0.surah.name == favorite.surah.name {
print("OMG FINALLY")
} else {
print("NOO NOO NOO")
}
//最终打印OMG。检查每个项目后。这正常吗?
答案 0 :(得分:2)
您要为实现NSObject
协议的Equatable
子类化,但默认情况下仅使用指针相等。您需要覆盖isEqual(_:)
方法和hash
属性:
override func isEqual(_ object: Any?) -> Bool {
guard let rhs = object as? Surah else { return false }
return number == rhs.number && name == rhs.name
}
override var hash: Int {
return number.hashValue ^ name.hashValue
}
let s1 = Surah(number: 1, name: "One")
let s2 = Surah(number: 1, name: "One")
s1 == s2 // => true
[s1] == [s2] // => true
答案 1 :(得分:0)
NSArray
是引用类型,因此您正在检查两个NSArray
指针是否相等。您应该使用本机的Swift Array
类型,它可以满足您的需求。
答案 2 :(得分:0)
如果将NSArray的 isEqual 用于自定义对象(不是来自SDK),则需要为该类型的对象实现isEqual。像这样:
//Make the service call:
let obs = this.httpClient.request(method, url, options);
//Return the observable:
return obs;