How can I sort a dictionary in Swift?
My Dictionary declaration:
var colorDictionary = Dictionary<Pixel, Int>() //pixel class stores RGB values of a pixel, Int stores the appearing times of the same color showing on the same image.
My target: I need the elements in the dictionary sorted by value (appearing times of colors) from high to low.
What I tried: I have done some research online, and I know the Dictionary in swift doesn't provide the sort function. So I wrote the following code:
var tempArray = Array(colorDictionary.keys)
var sortedKeys: () = sort(&tempArray){
var obj1 = self.colorDictionary[$0]
var obj2 = self.colorDictionary[$1]
return obj1>obj2
}
println("the most color: \(colorDictionary[tempArray[0])")
Output I got: "the most color: Optional(27)" //where 27 is the highest appearing time of the color, which is the value of the dictionary.
Question: How could I make it return the key as well?
My Pixel Class:
//for making the hashvalue stuff equatable
func ==(lhs: Pixel, rhs: Pixel) -> Bool {
return lhs.hashValue == rhs.hashValue
}
//customized class for storing pixel info of an image
class Pixel: Hashable {
//RGB components from one pixel
let r: CGFloat
let g: CGFloat
let b: CGFloat
var y: CGFloat = 0
var u: CGFloat = 0
var v: CGFloat = 0
var theUIColorOfThisPixel:UIColor
//adding for make the key hashable
var hashValue: Int {
return theUIColorOfThisPixel.hashValue
}
init(_thePixel: UIColor){
r = _thePixel.components.red
g = _thePixel.components.green
b = _thePixel.components.blue
theUIColorOfThisPixel=UIColor(red: r, green: g, blue: b, alpha: 1)
rgbToYuv(r, _g: g, _b: b)
}
}
[Problem solved] My solution: if I convert the result to Int (e.g. Int(colorDictionary[tempArray[0]]), it will just return the appearing time of the most common color on the image. For getting the UIColor of the pixel, I used:
var theMostUIColor: UIColor = tempArray[0].theUIColorOfThisPixel
I thought after storing my dictionary to the Array, it will just store the values. But now I found it actually stores the keys as well. Thanks for all the people who replied on this post. I appreciate!