Created
April 12, 2017 03:37
-
-
Save RodolfoAntonici/8ac0c719de45a75be605d8e58f7cc232 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
extension Array { | |
func insertionIndexOf(elem: Element, isOrderedBefore: (Element, Element) -> Bool) -> Int { | |
var lo = 0 | |
var hi = self.count - 1 | |
while lo <= hi { | |
let mid = (lo + hi)/2 | |
if isOrderedBefore(self[mid], elem) { | |
lo = mid + 1 | |
} else if isOrderedBefore(elem, self[mid]) { | |
hi = mid - 1 | |
} else { | |
return mid // found at position mid | |
} | |
} | |
return lo // not found, would be inserted at position lo | |
} | |
} | |
struct Product { | |
var ordemMobile: Int = 0 | |
var tituloMobile: String = "" | |
var categoryId = [Int]() | |
var valorMoeda: Int! | |
} | |
let products = [Product(ordemMobile: 4, tituloMobile: "Resgate quantas vezes quiser²", categoryId: [1, 2], valorMoeda: 500), | |
Product(ordemMobile: 0, tituloMobile: "", categoryId: [1, 2], valorMoeda: 500), | |
Product(ordemMobile: 6, tituloMobile: "Resgate quantas vezes quiser²", categoryId: [1, 2], valorMoeda: 1000), | |
Product(ordemMobile: 1, tituloMobile: "Lote Exclusivo", categoryId: [2], valorMoeda: 1000), | |
Product(ordemMobile: 2, tituloMobile: "Aproveite o lote promocional¹", categoryId: [1, 2], valorMoeda: 2000), | |
Product(ordemMobile: 3, tituloMobile: "Aproveite o lote promocional¹", categoryId: [1, 2], valorMoeda: 4000), | |
Product(ordemMobile: 7, tituloMobile: "Oferta Especial³", categoryId: [1, 2], valorMoeda: 10000), | |
Product(ordemMobile: 8, tituloMobile: "", categoryId: [1, 2], valorMoeda: 12000)] | |
var orderedProducts = [String: [Product]]() | |
for currentProduct in products { | |
if var currentKeyArray = orderedProducts[currentProduct.tituloMobile] { | |
let index = currentKeyArray.insertionIndexOf(elem: currentProduct) { $0.ordemMobile < $1.ordemMobile } | |
currentKeyArray.insert(currentProduct, at: index) | |
orderedProducts[currentProduct.tituloMobile] = currentKeyArray | |
} | |
else { | |
orderedProducts[currentProduct.tituloMobile] = [currentProduct] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment