按数组之一的顺序对两个数组进行排序 [Swift 3.0 - Xcode 8]

Sorting two arrays by the order of one of the arrays [Swift 3.0 - Xcode 8]

var ArrayToShowInTable = [String]()

我有两个数组:

let list = ["Carrot", "Apple", "Toothbrush", "Pear", "Oranges"]
let price = [3.50, 2.50, 1.50, 3.25, 4.25]

我想按价格(从小到大)对这两个数组进行排序, 所以我得到类似的东西:

list = ["Toothbrush", "Apple", "Pear", "Carrot", "Oranges"]
price = [1.50, 2.50, 3.25, 3.50, 4.25]

所以我可以让他们加入他们

for i in 0...list.count-1{
let join = list[i] += "\(price[i])"
ArrayToShowInTable.append(join)
}

然后在 TableView 中呈现它

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return (ArrayToShowInTable.count)
}


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "TableCell")
        cell.textLabel?.text = ArrayToShowInTable[indexPath.row] as? String
    return (cell)

有办法吗? 也许使用结构并打印到 table?

请帮忙??

您可以使用字典数组。

let list = ["Carrot" : 3.50, "Apple" : 2.50, "Toothbrush" : 1.50, "Pear" : 3.25 , "Oranges" : 4.25]
let sortedList = fruitsDict.sorted{ [=10=].value < .value }

你为什么不创建对象:

class Product{
    var price : Double = 0.0
    var name: String =""
    init(price:Double, name:String) {
         self.price = price
         self.name = name
    }
}

然后你可以声明你的数组:

var arrayToShowInTable = [Product]()

您只能使用 arrayToShowInTable

arrayToShowInTable = [Product(price:3.5, name:"Carrot"), Product(price:2.5 ,name: "Apple"), Product(price: 1.5,name: "Toothbrush"), Product(price: 3.25, name: "Pear"), Product(price: 4.25,name: "Oranges")]

然后,您可以按如下方式排序:

arrayToShowInTable = arrayToShowInTable.sorted({[=13=].price < .price})

创建 Dictionary 以匹配 ProductsPrices。处理数组很难处理。

let product = ["Carrot" : 3.50, "Apple" : 2.50, "Toothbrush" : 1.50, "Pear" : 3.25, "Oranges" : 4.25]


var sortedItem = product.sorted { ( first : (key: String, value: Double), second:(key: String, value: Double)) -> Bool in
    return first.value < second.value
}

var productList = [String]()
var priceList =  [Double]()

for (key, value) in sortedItem  {
    productList.append(key)
    priceList.append(value)
}

print(productList)
print(priceList)

你可以使用字典,这样价格和名字就会同步,你就不用担心排序后同步它们的位置了。

使用sorted函数对字典进行排序,然后在table视图函数中使用。

let pricesList = ["Carrot": 3.50, "Apple": 2.50, "Toothbrush": 1.50, "Pear": 3.25, "Oranges": 4.25]

var result = pricesList.sorted(by: {(a,b) in
    a.value as Double! < b.value as Double!

}) //or sorted{ [=10=].value < .value }

在表视图中:

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return result.count
}


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "TableCell")
        cell.textLabel?.text = "\(result[i].key) \(result[i].value)"
    return (cell)

如果您必须使用两个数组,您可以从这两个数组创建字典。 如果您不会使用字典,请告诉我。