gpt4 book ai didi

swift - 如何在 Swift 中对字典进行排序

转载 作者:行者123 更新时间:2023-11-30 14:14:42 24 4
gpt4 key购买 nike

如何在 Swift 中对字典进行排序?

我的词典声明:

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.

我的目标:我需要字典中的元素按值(颜色出现次数)从高到低排序。

我尝试过的:我在网上做了一些研究,我知道 swift 中的字典不提供排序功能。所以我写了下面的代码:

 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])")

我得到的输出:“the most color:Optional(27)”//其中27是该颜色出现的最高次数,也就是字典的值。

Question: How could I make it return the key as well?

我的像素类别:

//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)



}
}

[问题已解决]我的解决方案:如果我将结果转换为 Int (例如 Int(colorDictionary[tempArray[0]]),它只会返回图像上最常见颜色的出现时间。为了获取像素的 UIColor,我使用:

var theMostUIColor: UIColor = tempArray[0].theUIColorOfThisPixel 

我认为将字典存储到数组后,它只会存储值。但现在我发现它实际上也存储了 key 。感谢所有回复这篇文章的人。我很感激!

最佳答案

关于swift - 如何在 Swift 中对字典进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31335850/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com