按属性排序的数组

时间:2017-04-05 07:48:37

标签: arrays swift

我有一组像这样的对象数组:

[ProductDetails(name: "Tai Tou Choy",
    productDescription: "",
    deliveryTime: "24 hours",
    img1: "https://api.com.my/images/data/4983-img1-1463122485.jpg",
    thumbImg1: "https://api.com.my/images/data/thumbs/4983-img1-1463122485.jpg",
    img2: "",
    thumbImg2: "",
    img3: "",
    thumbImg3: "",
    videoLink: "",
    sku: "0000000004983",
    relatedProduct: "",
    priceOption: [PriceOption(id: 9931,
                            label: "500g",
                            price: "4.56",
                            promo: "0",
                            quantity: 999)],
    deliveryZone: [DeliveryZone(zone: "3")],
    deliveryZoneName: [DeliveryZoneName(zoneName: "Within Klang Valley")],
    qrCode: "4983"),
ProductDetails(name: "Penguin Asam Jawa",
    productDescription: "",
    deliveryTime: "24 hours",
    img1: "https://api.com.my/images/data/1004-img1.jpg",
    thumbImg1: "https://api.com.my/images/data/thumbs/1004-img1.jpg",
    img2: "",
    thumbImg2: "",
    img3: "",
    thumbImg3: "",
    videoLink: "",
    sku: "0000000001004",
    relatedProduct: "",
    priceOption: [PriceOption(id: 6971,
                            label: "1 kg",
                            price: "4.80",
                            promo: "0",
                            quantity: 864)],
    deliveryZone: [DeliveryZone(zone: "3")],
    deliveryZoneName: [DeliveryZoneName(zoneName: "Within Klang Valley")],
    qrCode: "1004")]

我想从数组上方进行价格排序,PriceOption数组也作为对象数组存储在主数组中。我如何从PriceOption进行排序?我试着这样做:

    for i in self.productList{

        i.priceOption.sortInPlace{

            $0.price.localizedCaseInsensitiveCompare($1.price) == NSComparisonResult.OrderedDescending
        }
    }

返回错误“不能在不可变值上使用变异成员:'i'是'let'常量。”

怎么做?

3 个答案:

答案 0 :(得分:2)

这是我如何解决您提出的问题。我正在使用数组类的sorted方法。

解决方案:

self.productList.sorted{ Float($0.priceOption.first!.price)! > Float($1.priceOption.first!.price)!  }

答案 1 :(得分:1)

试试这个

for i in self.productList {
    i.priceOption.sort { $0.price < $1.price } }

答案 2 :(得分:0)

swift 3的答案如下:

升序:

self.productList = self.productList.sorted(by: 
                 {(first: ProductDetails, second: ProductDetails) -> Bool in
                   first.price > second.price
                 }
              )

降序:

self.productList = self.productList.sorted(by: 
                 {(first: ProductDetails, second: ProductDetails) -> Bool in
                   first.price > second.price
                 }
              )