数组如何通过Swift的多属性排序?

时间:2019-06-03 08:24:33

标签: arrays swift sorting

我想按数字值对数组数据进行排序,例如“ 90> 80> 70 ...> 10”。
但是我不知道如何比较多重属性。

struct Item {
   let number1: Double
   let number2: Double
   let number3: Double
}

let item1 = Item(number1:0, number2:0, number3:10)
let item2 = Item(number1:20, number2:0, number3:0)
let item3 = Item(number1:0, number2:30, number3:0)
let item4 = Item(number1:0, number2:0, number3:40)
let item5 = Item(number1:0, number2:50, number3:0)
let item6 = Item(number1:60, number2:0, number3:0)
let item7 = Item(number1:0, number2:70, number3:0)
let item8 = Item(number1:0, number2:0, number3:80)
let item9 = Item(number1:0, number2:90, number3:0)

var array:[Item] = [item1, item2, item3, item4, item5, item6, item7, item8, item9]

array = array.sorted { (item, nextItem) -> Bool in {
     item.number3 < nextItem.number3 //how to add item's number2 & number1 into here.
}

1 个答案:

答案 0 :(得分:1)

将元素按3个数字之和排序

array = array.sorted { (item, nextItem) -> Bool in
    let itemSum = item.number1 + item.number2 + item.number3
    let nextItemSum = nextItem.number1 + nextItem.number2 + nextItem.number3
    return itemSum > nextItemSum
}
  

[Item(数字1:0.0,数字2:90.0,数字3:0.0),
  物品(1号:0.0,2号:0.0,3号:80.0),
  物品(数字1:0.0,数字2:70.0,数字3:0.0),
  项目(数字1:60.0,数字2:0.0,数字3:0.0),
  项目(编号1:0.0,编号2:50.0,编号3:0.0),
  物品(1号:0.0,2号:0.0,3号:40.0),
  项目(编号1:0.0,编号2:30.0,编号3:0.0),
  项目(数字1:20.0,数字2:0.0,数字3:0.0),
  项目(数字1:0.0,数字2:0.0,数字3:10.0)]