我正在寻找对ChangeArray进行排序的方法,以便按从高到低的顺序显示库存,我已经使用变量sortChange完成了此操作,但是BidArray和Stock Array与新数据不对应。我该如何解决。谢谢。

    var StockArray = [String]()
    var BidArray = [Double]()
    var ChangeArray = [Double]()




    @IBOutlet weak var tableView: UITableView!


//    @IBOutlet weak var StockSymbolLbl: UILabel!
//    @IBOutlet weak var BidSymbolLbl: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        getJSON()
        automaticallyAdjustsScrollViewInsets = false
        tableView.dataSource = self
        tableView.delegate = self
        tableView.registerNib(UINib(nibName: "StockHome", bundle: NSBundle.mainBundle()),forCellReuseIdentifier: "stockHome")
        tableView.rowHeight = 60
//        StockSymbolLbl.text = ""
//        BidSymbolLbl.text = ""


        }



    func getJSON(){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
        let url = NSURL(string: self.stockURL)
        let request = NSURLRequest(URL: url!)
        let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
        let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in

            if error == nil {

                let swiftyJSON = JSON(data: data!)
                let Symbol: String? = swiftyJSON["query"]["results"]["quote"][0]["symbol"].stringValue
                let bid: String? = swiftyJSON["query"]["results"]["quote"][0]["Bid"].stringValue
                let change: String? = swiftyJSON["query"]["results"]["quote"][0]["Change"].stringValue
                print(change!)
                print(Symbol!)
                print(bid!)
                dispatch_async(dispatch_get_main_queue()) {
//                self.StockSymbolLbl.text? = "\(Symbol!)"
//                self.BidSymbolLbl.text? = "\(bid!)"
                    self.NumberofRows = swiftyJSON["query"]["results"]["quote"].count

                    for i in 0...self.NumberofRows {
                        var stockcount = 0
                        stockcount += i
                        let Stock = swiftyJSON["query"]["results"]["quote"][stockcount]["symbol"].stringValue
                        let Bid = swiftyJSON["query"]["results"]["quote"][stockcount]["Bid"].doubleValue
                        let Change = swiftyJSON["query"]["results"]["quote"][stockcount]["Change"].doubleValue

                        self.StockArray.append(Stock)
                        print(Stock)
                        self.BidArray.append(Bid)
                        print(Bid)
                        self.ChangeArray.append(Change)
                        print(Change)
                    }
                    self.tableView.reloadData()
                }



            }else{
                print("There was an error")
            }

        }
        task.resume()
    }

}
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return NumberofRows
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell: StockHome = tableView.dequeueReusableCellWithIdentifier("stockHome", forIndexPath: indexPath) as! StockHome

        if StockArray.count != 0{
            let sortChange = ChangeArray.sort(>)
            cell.symbolLbl?.text = StockArray[indexPath.row]
            let bid = BidArray[indexPath.item]
            let changeRate = ChangeArray[indexPath.row]
            cell.bidLbl?.text = "\(bid)" + " USD "
            cell.changeLbl?.text = "\(changeRate)" + " %"

        }

        print(self.StockArray)

        return cell
    }
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        switch ChangeArray[indexPath.row] {
        case let x where x < 0.0:
            cell.backgroundColor = UIColor(red: 255.0/255.0, green: 59.0/255.0, blue: 48.0/255.0, alpha: 1.0)
        case let x where x > 0.0:
            cell.backgroundColor = UIColor(red: 76.0/255.0, green: 217.0/255.0, blue: 100.0/255.0, alpha: 1.0)
        case let x:
            cell.backgroundColor = UIColor(red: 44.0/255.0, green: 186.0/255.0, blue: 231.0/255.0, alpha: 1.0)
        }
        cell.textLabel!.textColor = UIColor.whiteColor()

        }


}

最佳答案

现在,您的三个阵列是独立的,因此不能保证顺序相同。

我要做的是使具有三个值的结构并将其附加到可以排序的单个数组中。

struct Stock {
     var symbol: String = ""
     var bid: Double = 0.0
     var change: Double = 0.0
}


现在,您可以像这样在getJSON()中重写for循环:

for i in 0..<self.NumberofRows {
    let symbol = swiftyJSON["query"]["results"]["quote"][i]["symbol"].stringValue
    let bid = swiftyJSON["query"]["results"]["quote"][i]["Bid"].doubleValue
    let change = swiftyJSON["query"]["results"]["quote"][i]["Change"].doubleValue
    let stock = Stock(symbol: symbol, bid: bid, change: change)
    stockArray.append(stock)
}


现在,您应该可以使用以下方式对“ StockArray”进行排序:

stockArray = stockArray.sort({
    return $0.change > $1.change
})


稍微偏离主题:一些技巧

尝试使变量名的首字符不大写,类/枚举/结构的首字符大写。同一变量名中的每个新单词都应大写。

其次,尝试将for循环重写为for-each循环。 some documentation。这更清洁,并且不再需要NumberofRows。由于现在所有内容都在1个数组中,因此您可以在stockArray.count中使用numberOfRowsInSection

您可以在调用tableView.reloadData()之前立即进行排序,这样,它仅排序一次,而不是每次加载单元格时都进行排序。

最后,尝试使用可能会更改的JSON时使用if let,这样您可以确定要当作Double的实际上是Double。 Some documentation

关于arrays - 成功对三个数组之一进行排序后,如何对其他数组进行排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38690190/

10-12 00:15
查看更多