如何将字典应用于数组以使其正确排序?

时间:2017-11-04 00:02:48

标签: arrays swift sorting dictionary key

这是一个快速的游乐场,最终目标是使用Months: [String]数组对字典进行排序。以下是代码现在的样子:

Class YearlyTemps { 
    var Months: [String] = ["January", "February"...]
    var Temperatures: [String,(temp1: Int, temp2: Int)] = [:]     
    func SetMonthlyTemps(month: String, temp1: Int, temp2: Int) -> Void { 
        Temps [month] = (low, high)
    } 
    func ShowResult() -> Void {
        for key in Temps.key{
            print(key)
        }
        for values in Temps.value{
            print(values)
        }
    }
}

它目前将字典显示为:

December
November
January

(23, 40)
(20, 55)
(-2, 34)

没有真正的订单。我需要它按顺序排列(1月到12月,温度在同一行):

January (-2, 34)    
November (20, 55)    
December (23, 40)

我已经尝试将字典推入一个没有运气的数组中。而且我不确定我是否应该在Months数组中有默认值,或者是否应该在SetMonthlyTemps函数中填充它。

2 个答案:

答案 0 :(得分:0)

您可以使用

迭代键值对
for entry in Temps {
    print("\(entry.key) \(entry.value)")
}

此外,您可以按照使用.sorted(by: )对数组进行排序的方式对字典进行排序。一切都会给出

for entry in Temps.sorted(by: { $0.key < $1.key }) {
    print("\(entry.key) \(entry.value)")
}

现在,由于您希望按月对它们进行排序,因此您需要告诉您的代码含义。最简单的方法是,使用String类型定义它们,而不是在几个月内使用enum个变量。此外,如果您为枚举选择Int作为rawValue,则会按照您在枚举中定义它们的方式自动排序。这将是这样的:

enum Month: Int {
    case january
    case february
    case march
    ...
    case december
}

然后,您只需将Temps变量更改为[Month: (Int, Int)]类型,而不是[String: (Int, Int)]。最后,您只需使用

即可
for entry in Temps.sorted(by: { $0 < $1 }) {
    print("\(entry.key) \(entry.value)")
}

最后,我建议使用小写的camelCase作为变量名。

答案 1 :(得分:0)

字典没有快速订购以及许多其他语言。如果你有一个名为monthsArray的所有月份名称的数组,我会迭代它并使用每个索引的值作为键来从字典中获取值。

var monthsArray = ["January", "November", "December"]
var tempsDict: [String : (Int, Int)] = [:]

tempsDict["November"] = (11, 11)
tempsDict["January"] = (1, 1)
tempsDict["December"] = (12, 12)

for month in monthsArray {
    //Check to make sure dictionary has key
    if let temps = tempsDict[month] {
        print("\(month): \(temps)")
    }
}