ios - 如何删除Xcode中类的arraylist中的重复项
问题描述
我正在尝试使用 json 和 api 从我的网络服务器获取数据,并将它们放入我的应用程序中,服务器中的数据是重复的,我想删除重复的数据,所以现在这是我的数据类,它称为 TypeItems 类
import Foundation
class TypeItems {
var car_type:String?
var type:String?
var model:String?
var ph:String?
init(car_type:String, type:String, model:String, ph:String) {
self.car_type = car_type
self.type = type
self.model = model
self.ph = ph
}
}
这是我的主要课程
import UIKit
class TypeViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
var Item = Array<TypeItems>()
var itemsUrl = ""
var CarType:String?
@IBOutlet weak var CollectionViewList: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
itemsUrl = "http://mydpmen/reportall.php?car_type=\(CarType!)"
print(itemsUrl)
ReadFromUrl(url: itemsUrl)
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return Item.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell:TypeCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "typecell", for: indexPath) as! TypeCollectionViewCell
cell.SetImage(url: Item[indexPath.row].ph!)
cell.laCarType.text = Item[indexPath.row].car_type! + " " + Item[indexPath.row].type!
cell.laModel.text = Item[indexPath.row].model
return cell
}
func ReadFromUrl(url:String) {
DispatchQueue.global().async {
do {
let newUrl = url.replacingOccurrences(of: " ", with: "%20")
let AppUrl = URL(string: newUrl)!
let data = try Data(contentsOf: AppUrl)
let json = try JSONSerialization.jsonObject(with: data) as! [[String:Any]]
print(json)
DispatchQueue.global().sync {
for item in json {
let photo = "http://mydomen/photo/Cars/\(item["car_type"]!) \(item["type"]!) \(item["model"]!).png"
let newPhoto = photo.replacingOccurrences(of: " ", with: "%20")
print("newphoto is \(newPhoto)")
self.Item.append(TypeItems(car_type: item["car_type"]! as! String, type: item["type"]! as! String, model: item["model"]! as! String, ph: newPhoto))
self.CollectionViewList.reloadData()
}
}
} catch {
print("cannot load from server!")
}
}
}
}
现在我只想从列表中删除重复的项目,我想按 car_type 和类型和型号排序,如果项目重复,我想删除它
解决方案
在ReadFromUrl
方法中,在重新加载集合视图之前写下一行。
let objectSet = Set(Item.map { $0.model })
这将创建一个带有数组的集合。现在将此集合用于集合视图数据源和委托。
$0.model
注意: 1.您可以用重复的键替换模型。2. 遵循命名约定。变量名以小写字母开头。
推荐阅读
- mysql - 如何使用 Responsys MYSQL 在接下来的两周内过生日
- django - 将数据传递给表单(来自 POST 和 url)
- git - Git:如何将“合并远程跟踪分支”重新定位并压缩到以后的提交?
- vb.net - 如何获取本地 IP 地址?
- html - 在 Jquery 中自行打开 Aссordion
- linux - Git 从远程计算机将存储库拉到本地计算机
- c++ - 使用 Google test API for C++ 通过参数化单元测试来测试私有方法的可能方法是什么?
- python - 我试图安装 ttn 包,但我不能
- c++ - 如果我对循环进行以下更改,执行时间会减少吗?
- javascript - 如何验证两个以 ; 分隔的电子邮件 ID 使用 jquery/javascript