我有一个存储日期的String数据。例如:
let dates = ["1-Jan-2015", "1-Feb-2015", "20-Mar-2014", "15-Apr-2014", "12-May-2013", "23-Jun-2012"]
我需要计算当年发生的次数,然后存储它。所以我需要的就是那样的
let years = ["2015" : 2, "2014" : 2, "2013" : 1, "2012" : 1]
我想避免对未来的增长进行硬编码。意思是说,如果我有2020年,我不能多年来难以存储这些值。
所以这里的问题是我不知道我应该如何在概述上做到这一点。另外,如何将String格式转换为日期?
答案 0 :(得分:2)
let dates = ["1-Jan-2015", "1-Feb-2015", "20-Mar-2014", "15-Apr-2014", "12-May-2013", "23-Jun-2012"]
// map the last 4 characters of your string
let years = dates.map{String($0.characters.suffix(4))}
// create a dictionary to store tue frequency
var frequencies:[String:Int] = [:]
// loop through the years
for year in years {
// increase it
frequencies[year] = (frequencies[year] ?? 0) + 1
}
let sortedFrequencies = frequencies.sort{ $0.0 < $1.0 }
print(sortedFrequencies) // [("2012", 1), ("2013", 1), ("2014", 2), ("2015", 2)]\n"
答案 1 :(得分:0)
我创建了以下解决方案。使用以下功能,它将在屏幕截图中提供以下结果
/// This function will return the array as per your requirement
func getyears(dates: NSArray) -> NSArray
{
var year = [String]()
let newdates = dates
var countvalue = 0
for i in dates {
let x = i.stringByReplacingOccurrencesOfString("-", withString: "")
let startIndex = x.endIndex.advancedBy(-4)
let lastFourDigitsOfdate = x.substringFromIndex(startIndex)
for xm in newdates
{
let xy = xm.stringByReplacingOccurrencesOfString("-", withString: "")
let startIndex1 = xy.endIndex.advancedBy(-4)
let lastFourDigitsOfdate1 = xy.substringFromIndex(startIndex1)
if lastFourDigitsOfdate == lastFourDigitsOfdate1
{
countvalue = countvalue + 1
}
}
year.append("\(lastFourDigitsOfdate) : \(countvalue)")
countvalue = 0
}
return getUniqArrayData(year)
}
// This function will be required to get an unque array
func getUniqArrayData<S: SequenceType, E: Hashable where E==S.Generator.Element>(source: S) -> [E] {
var seen: [E:Bool] = [:]
return source.filter { seen.updateValue(true, forKey: $0) == nil }
}
let dates = ["1-Jan-2015", "1-Feb-2015", "20-Mar-2014", "15-Apr-2014", "12-May-2013", "23-Jun-2012"]
//Calling the above function
getyears(dates)
希望这会有所帮助。