【问题标题】:How to sort an array of posts by their elements?如何按元素对帖子数组进行排序?
【发布时间】:2020-07-28 19:09:47
【问题描述】:

我有一个应用程序,用户可以在其中搜索待售商品。我目前正在尝试添加功能,以便用户可以查看按价格从低到高排序的项目。在用户点击排序按钮后,他们会看到另一个显示不同排序选项的视图控制器。第一个是“价格:从低到高”。在从低到高被点击后,我使用协议发回一个函数并委托给当前的 ResultsTableViewController 。一切正常,直到我尝试根据价格进行排序。当我print(data) 我回来了

[app.UserPostData(id: Optional("61E93673-24B8-42BE-B0AA-7185A0F26A39"), userSub: Optional("e345fdac-7eb5-4cde-a421-aa758b05d999"), fileName: Optional("823AD3EF-2890-40C4-A1F2-47FCDDA5A64B"),userPostedImage: Optional(<UIImage:0x600002e9b330 anonymous {1239, 1241}>), description: Optional("example description"), dateUploaded: Optional("2020-07-28")), app.UserPostData(id: Optional("9373925E-5526-4D92-B104-7981CD226669"), userSub: Optional("e345fdac-7eb5-4cde-a421-aa758b05d999"), fileName: Optional("0703758F-60AE-4566-A0A0-0EF16C1711BE"), price: Optional(50000),userPostedImage: Optional(<UIImage:0x600002e9fb10 anonymous {1238, 1240}>), description: Optional("example description"), dateUploaded: Optional("2020-07-28")), app.UserPostData(id: Optional("0FC678A6-B308-4A05-8B36-093768375A79"), userSub: Optional("e345fdac-7eb5-4cde-a421-aa758b05d999"), fileName: Optional("555ADDD0-5E58-4577-A2FD-52B6F47AC747"), price: Optional(650), userPostedImage: Optional(<UIImage:0x600002e80240 anonymous {1238, 1240}>), description: Optional("example description"), dateUploaded: Optional("2020-07-27"))]

如何将数组排序/重新排列为价格从低到高显示的项目?在我的排序函数中,我收到一条错误消息 Binary operator '&gt;' cannot be applied to two 'Int?' operands

struct UserPostData {
    var id: String?
    var userSub: String?
    var fileName: String?
    var price: Int?
    var userPostedImage: UIImage?
    var description: String?
    var dateUploaded: String?
}


class ResultsTableViewController: UITableViewController, priceLowToHigh, priceHightoLow {
    func sortPriceLowToHigh(sort: String) {
        print(sort)
         print(data)
            data.sort(by: { $0.price > $1.price}) // This is where I get the error 
    }
    func sortPriceHighToLow(sort: String) {
        print(sort)
    }
  
    var data: [UserPostData] = []
    var userSubID = String()
    let activityIndicator = UIActivityIndicatorView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setView()
        getData()
    }
    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return data.count
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "Results") as! CellResults
        cell.image = data[indexPath.section].userPostedImage
        cell.price = data[indexPath.section].price
        cell.layoutSubviews()
        self.tableView.rowHeight = UITableView.automaticDimension
        return cell
    }
    func setView(){
        let sortButton = UIBarButtonItem(title: "Sort", style: .plain, target: self, action: #selector(sortPressed))
        navigationItem.rightBarButtonItem = sortButton
    }
    func getData(){
        activityIndicator.hidesWhenStopped = true
        activityIndicator.translatesAutoresizingMaskIntoConstraints = false
        activityIndicator.style = .large
        activityIndicator.startAnimating()
        tableView.addSubview(activityIndicator)
        NSLayoutConstraint.activate([activityIndicator.centerXAnchor.constraint(equalTo: tableView.safeAreaLayoutGuide.centerXAnchor),
                                     activityIndicator.centerYAnchor.constraint(equalTo: tableView.safeAreaLayoutGuide.centerYAnchor)])
        userSubID = AWSMobileClient.default().userSub!
        
        let post = Post.keys
        let predicate = post.search == search
        _ = Amplify.API.query(request: .list(SellerPost.self, where: predicate)) { event in
            switch event {
            case .success(let result):
                switch result {
                case .success(let posts):
                    DispatchQueue.main.async {
            
                        self.tableView.reloadData()
     
                        for element in posts{
                            _ = Amplify.Storage.downloadData(key: element.filename,progressListener: { progress in
                                print("Progress: \(progress)")},
                                                             resultListener: { (event) in
                                                                switch event {
                                                                case let .success(data):
                                                                    DispatchQueue.main.async {
                                                                        
                                                                        
                                                                        self.data.append(UserPostData.init(id: element.id, userSub: element.userSub, fileName: element.filename, price: element.price, userPostedImage: UIImage(data: data), description: element.description,dateUploaded: element.dateUploaded))
                                                                        self.tableView.reloadData()
                                                                        self.activityIndicator.stopAnimating()
                                                                    }
                                                                    print("Completed: \(data)")
                                                                case let .failure(storageError):
                                                                    print("Failed: \(storageError.errorDescription). \(storageError.recoverySuggestion)")
                                                                }
                            })
 
                        }
                        
                    }
                case .failure(let error):
                    print("Got failed result with \(error.errorDescription)")
                }
            case .failure(let error):
                print("Got failed event with error \(error)")
            }
        }
        
        self.tableView.register(CellResults.self, forCellReuseIdentifier: "Results")
        
    }
 
    @objc func sortPressed(){
        print("sort clicked")
        let sTVC = SortViewController()
        sTVC.priceLowToHighDelegate = self
        sTVC.priceHighToLowDelegate = self
        sTVC.modalPresentationStyle = .custom
        self.present(sTVC, animated: true, completion: nil)
    }
}

【问题讨论】:

    标签: swift


    【解决方案1】:

    您不能使用可选值进行排序,因此如果它为 nil,则需要使用 ?? 提供默认值。对于排序最小值或最大值是最合适的。如果您想对 nil 值进行最后排序或对相反的最大值排序,请使用 min

    data.sort(by: { $0.price ?? Int.min > $1.price ?? Int.min })
    

    【讨论】:

    • 如何打印才能按顺序显示?当我print(data.sort(by: { $0.price ?? Int.min &gt; $1.price ?? Int.min })) 调试控制台显示()
    • sort 不返回任何内容,然后打印data
    • 我做错了什么吗?我按此订单返回价格(50000)(850)(650)
    • 是的,您没有阅读文档 :)。如果要按升序排序,请将 > 更改为
    猜你喜欢
    • 2019-09-01
    • 1970-01-01
    • 2016-10-11
    • 2016-02-01
    • 1970-01-01
    • 2017-12-16
    • 1970-01-01
    • 1970-01-01
    • 2015-06-28
    相关资源
    最近更新 更多