[英]cannot assign value of type '[(string, string)]' to type '[string : string]'
I've declared this dictionary: 我已经声明了这本词典:
var arrayFrasi:[String:String] = [:]
Then in the viewDidLoad I retrive the data from my db and then I sort the dictionary using this code: 然后在viewDidLoad中,我从数据库中检索数据,然后使用以下代码对字典进行排序:
let df = NSDateFormatter()
df.dateFormat = "dd-MM-yyyy"
let myArrayOfTuples = self.arrayFrasi.sort{ df.dateFromString($0.0)!.compare(df.dateFromString($1.0)!) == .OrderedAscending}
But I need to use the initial dictionary ( arrayFrasi) , when I do this: 但是在执行此操作时,我需要使用初始字典( arrayFrasi) :
self.arrayFrasi = myArrayOfTuples
I've got this error: 我有这个错误:
cannot assign value of type '[(string, string)]' to type '[string : string]'
无法将类型[[(string,string)]'的值分配给类型[[string:string]'
I can't figure out why. 我不知道为什么。 Thank you very much!
非常感谢你!
That makes perfect sense. 这是很合理的。 A Dictionary has no defined order, so the
sort
returns you an array of tuples. 字典没有定义的顺序,因此
sort
返回一个元组数组。
Swift's Dictionary type does not have a defined ordering.
Swift的Dictionary类型没有定义的顺序。 To iterate over the keys or values of a dictionary in a specific order, use the sort() method on its keys or values property.
若要以特定顺序遍历字典的键或值,请在其键或值属性上使用sort()方法。
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html
You need to Map it back into the same type 您需要将其映射回相同的类型
var arrayFrasi: [String: String] = [ "24-01-1991" : "VALUE" , "22-01-1991" : "VALUE" ]
let df = NSDateFormatter()
df.dateFormat = "dd-MM-yyyy"
let myArrayOfTuples = arrayFrasi.sort{ df.dateFromString($0.0)!.compare(df.dateFromString($1.0)!) == .OrderedAscending}.map { [$0.0 : $0.1] }.flatMap { $0 }
.reduce([String:String]()) { (dict, tuple) in
var dict = dict
dict.updateValue(tuple.1, forKey: tuple.0)
return dict
}
arrayFrasi = myArrayOfTuples // ["22-01-1991": "VALUE", "24-01-1991": "VALUE"]
Hope It Helps 希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.