作者:万万558 | 来源:互联网 | 2023-09-24 10:33
我需要使用for循环遍历Dictionary值(值=数组)。和
在每个数组中以相反的顺序排序。我该怎么办?
var a: [String : [String]]
预期结果如下:
["C": ["Camilla","Cecelia","Colette"],"B": ["Ben","Bob"],"A": ["Alex","Andy"]]
UPD:
我有功能:
func someFunc(array: [String]) -> [String : [String]] {
let groupedDictiOnary= Dictionary (grouping: array,by: { String($0.first!) }nc).filter{ $0.value.count > 1 }
我有一些数组:
var array = ["Camilla","Andy","Bob","Ben","Alex","Colette","Camilla"]
一旦通过分组从数组中创建了字典,就可以使用for循环来过滤大小和排序
func someFunc(array: [String]) -> [String : [String]] {
let groupedDictiOnary= Dictionary (grouping: array,by: { String($0.first!) })
var result: [String: [String]] = [:]
for (key,value) in groupedDictionary {
if value.count > 1 {
result[key] = value.sorted(by: >)
}
}
return result
}
,
字典没有顺序,但是您可以对键进行排序
var arr = Array(dic.keys)
arr.sort(by:>)
然后使用arr
访问字典
,
您可以这样做
let dictInitial = [ "A": ["Alex","Andy"],"C": ["Camilla","Cecelia","Colette"],"B": ["Ben","Bob"]]
let keys = Array(dictInitial.keys).sorted(by: >)
// get values
for key in keys {
print("KEY:",key,"VALUES :",dictInitial[key]!)
}
输出:
KEY: C VALUES : ["Camilla","Colette"]
KEY: B VALUES : ["Ben","Bob"]
KEY: A VALUES : ["Alex","Andy"]
,
@freddyK首先,您的someFunc
代码中存在逻辑错误。您必须首先增强它,因为只有两个对象具有相同的字母时,它才会创建一个组。应该像{ $0.value.count > 0 }
。
以下代码段可以为您提供帮助。
let objDict = someFunc(array: ["Zoro","Camilla","Andy","Bob","Ben","Alex","Colette","Camilla"])
let sortedDic = objDict.sorted { (aDic,bDic) -> Bool in
return aDic.key > bDic.key
}
print(sortedDic)
,
@freddyk您的更新问题是部分正确的。您只需要按字典键的降序对字典进行排序即可。但您需要将字典格式从[string:[string]]
更改为[(key: String,value: [String])]
两者相同,但是swift与数据类型高度相关,这就是为什么我们不能转换它的原因
var a: [String] = ["Ben","Alex"]
func someFunc(array: [String]) -> [(key: String,value: [String])] {
let groupDict = Dictionary (grouping: array,by: { String($0.first!) }).sorted { (str1,str2) -> Bool in
return str1.key.compare(str2.key) == .orderedDescending
}
return groupDict
}
let groupedDictiOnary= someFunc(array: a)
print(groupedDictionary)
所以它的输出将如下所示
输出:[(键:“ C”,值:[“ Camilla”,“ Cecelia”,“ Colette”]),(键:“ B”,值:[“ Ben”,“ Bob” ]),(键:“ A”,值:[“ Andy”,“ Alex”])]