2016-08-01 55 views
0

其中之一我正在尋找排序ChangeArray,以便它顯示從最高到最低的股票,我已經完成了與變量sortChange,但BidArray和庫存數組與新數據不符。我如何解決這個問題。謝謝。我如何排序其他數組時,我已經成功排序三個

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() 

     } 


} 

回答

0

現在你的三個數組是獨立的,因此不保證它們的順序相同。

我會做的是使三個值的結構,並將其追加到1個單一的數組,你可以排序。

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

現在你可以重寫爲的getJSON)環(像這樣:

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 
}) 

offtopic:一些提示

嘗試讓變量名的第一個字符不大寫,第一個字符大寫的類/枚舉/結構。同一個變量名中的每個新單詞都應該大寫。

其次,嘗試將for循環重寫爲for-each循環。 some documentation。這是更清潔,使NumberofRows不再需要。而且,由於現在一切都在1陣列,您可以使用stockArray.countnumberOfRowsInSection

你打電話tableView.reloadData()權之前,您可以做排序,這樣它只是整理一次,而不是每一個單元被裝載時間。

最後,在使用可能會更改的JSON時嘗試使用if let,這樣您就可以確定您將Double視爲Double的實際情況。 Some documentation

+0

當我添加stockArray.append(Stock)時,我得到一個錯誤,因爲stockArray數組只是一個字符串,我該如何解決這個問題? – Patty

+1

將'var StockArray = [String]()'更改爲'var StockArray = [Stock]()' – Houwert