我是swift的新手,将我的代码升级为swift 3。
Swift 2.3代码如下:
func sectionTite() {
let keyArray:NSArray = self.messageDictionary.allKeys
let sortedArray = keyArray.sortedArrayUsingComparator { (dateString1: AnyObject, dateString2: AnyObject) -> NSComparisonResult in
let d1:NSDate = NSDate.dateFromString(dateString1 as! String, fromFormat: NSDate.DateFormat.KYYYY_MM_DD)
let d2: NSDate = NSDate.dateFromString(dateString2 as! String, fromFormat: NSDate.DateFormat.KYYYY_MM_DD)
return (d1 ).compare(d2 )
}
self.sectionArray = sortedArray
}
Swift 3.0
func sectionTite() {
let keyArray:NSArray = self.messageDictionary.allKeys as NSArray
let sortedArray = keyArray.sortedArray (comparator: { (dateString1: AnyObject, dateString2: AnyObject) -> ComparisonResult in
let d1:Date = Date.dateFromString(dateString1 as! NSString , fromFormat: Date.DateFormat.KYYYY_MM_DD as NSString)
print(d1)
let d2: Date = Date.dateFromString(dateString2 as! NSString, fromFormat: Date.DateFormat.KYYYY_MM_DD as NSString)
return (d1 ).compare(d2 )
} as! (Any, Any) -> ComparisonResult)
self.sectionArray = sortedArray as NSArray
}
上面的代码崩溃了状态EXC_breakpoint(code1,subcode ...),它没有说明崩溃的原因。 keyArray由一个日期项组成.Below代码创建问题。
let keyArray:NSArray = self.messageDictionary.allKeys as NSArray
答案 0 :(得分:2)
使用原生swift类型Array
和Dictionary
代替NSArray
和NSDictionary
。因此,请将sectionArray
声明为[String]
而不是NSArray
var sectionArray = [String]()
现在按照这种方式对字典键进行排序。
if let dic = self.messageDictionary as? [String:Any] {
let keys = Array(dic.keys) as [String]
let dateForamatter = DateFormatter()
dateForamatter.dateFormat = Date.DateFormat.KYYYY_MM_DD //Set Your dateFormat
self.sectionArray = keys.sorted(by: { (str1, str2) -> Bool in
let date1 = dateForamatter.date(from: str1)! //I have force wrapped
let date2 = dateForamatter.date(from: str2)!
return date1 < date2
})
}
答案 1 :(得分:0)
let keyArray:NSArray = self.messageDictionary.allKeys as NSArray
let dateForamatter = DateFormatter()
dateForamatter.dateFormat = Date.DateFormat.KYYYY_MM_DD //Set Your dateFormat
self.sectionArray = keyArray.sorted(by: { (str1, str2) -> Bool in
let date1 = dateForamatter.date(from: str1 as! String)!
let date2 = dateForamatter.date(from: str2 as! String)!
return date1 < date2
}) as NSArray
self.sectionArray = keyArray as NSArray
}