我玩的是比较两个数据数组,每个数据都是从一个结构构建的。这背后的潜在想法是将本地数据与网络数据中的数组进行比较,如果它们相同,则使用本地数据来节省时间,特别是当某些数据是图像时。比较2结构阵列
我嘲笑测试的基本代码是低于,但我似乎无法比较数组,因为它们来自一个结构?有没有解决的办法?
func compareQuery() {
struct packStructNW {
var packName : String
var packDescription : String
var packTitle : String
var packImage : PFFile
var packID: String
}
var packArrayNW = [packStructNW]()
struct packStructLDS {
var packName : String
var packDescription : String
var packTitle : String
var packImage : PFFile
var packID: String
}
var packArrayLDS = [packStructLDS]()
if self.connected {
let packQueryNW = PFQuery(className: "Pack")
packQueryNW.order(byAscending: "packName")
packQueryNW.findObjectsInBackground(block: { (objectsArray, error) in
if error != nil {
print(error!)
} else {
if let packs = objectsArray {
for object in packs {
let arrayName = object.object(forKey: "packName") as! String
let arrayDescription = object.object(forKey: "packDescription") as! String
let arrayTitle = object.object(forKey: "packTitle") as! String
let arrayImage = object.object(forKey: "packImage") as! PFFile
let arrayID = object.objectId as String!
packArrayNW.append(packStructNW(packName: arrayName, packDescription: arrayDescription, packTitle: arrayTitle, packImage: arrayImage, packID: arrayID!))
}
}
}
})
let packQueryLDS = PFQuery(className: "Pack")
packQueryLDS.order(byAscending: "packName")
packQueryLDS.fromLocalDatastore()
packQueryLDS.findObjectsInBackground(block: { (objectsArray, error) in
if error != nil {
print(error!)
} else {
if let packs = objectsArray {
for object in packs {
let arrayName = object.object(forKey: "packName") as! String
let arrayDescription = object.object(forKey: "packDescription") as! String
let arrayTitle = object.object(forKey: "packTitle") as! String
let arrayImage = object.object(forKey: "packImage") as! PFFile
let arrayID = object.objectId as String!
packArrayLDS.append(packStructLDS(packName: arrayName, packDescription: arrayDescription, packTitle: arrayTitle, packImage: arrayImage, packID: arrayID!))
}
}
}
})
print(packArrayNW)
print(packArrayLDS)
if packArrayLDS == packArrayNW {
print("they are the same")
} else {
print("they are different")
}
}
}
-----------------编辑--------------------
谢谢解决方案WERUreo。
最后,我不得不将可equatable部分移动到结构的扩展才能使其工作。我确信你所展示的方式确实有效,但我不能没有错误地发生。
它比较数组,只有我现在遇到的问题是,我正在运行比较代码,因为我在后台获取数据时,数组没有完全填充。任何想法在运行代码比较之前如何等待数组填充?
主类
struct myStruct {
var packName : String
var packDescription : String
var packTitle : String
var packImage : PFFile
var packID: String
}
内部主类
extension PackViewController.myStruct: Equatable {}
func ==(lhs: PackViewController.myStruct, rhs: PackViewController.myStruct) -> Bool {
let areEqual = lhs.packName == rhs.packName &&
lhs.packDescription == rhs.packDescription &&
lhs.packTitle == rhs.packTitle &&
lhs.packImage === rhs.packImage &&
lhs.packID == rhs.packID
return areEqual
}
该代码是否编译?如果是这样,我觉得我们错过了图片的一部分。你试图比较两个不同的数组,每个数组都拥有两种不同的类型。这应该是失败吧... – WERUreo
哈哈不,它不。 – Pippo