使用自定义对象swift 4对数组进行排序

时间:2017-11-06 12:06:22

标签: arrays swift sorting

public class OfferObjectModel: JSONJoy {
    let rank : Int?
    }

offersList.sort(by: { $0.rank < $1.rank }) -->Binary operator '<' cannot be applied to two 'Int?' operands
offersList is an array of OfferObjectModel

1 个答案:

答案 0 :(得分:0)

您可以这样做:

a.sort { (first, second) -> Bool in
guard let firstRank = first.rank else { return true }
guard let secondRank = second.rank else { return false }
return firstRank < secondRank
}

因此,此代码块将确保您的nil排名首先,然后按排名值排序。如果改变这一部分:

guard let firstRank = first.rank else { return false }
guard let secondRank = second.rank else { return true }

Nil排名将在最后。 请确保您的阵列是可变的。