我正在尝试用swift构建我的第一个应用程序,并希望找到数组中与当前月份相关的部分的总和。这是我的代码:
struct Hour {
var date: String?
var time: String?
init(date: String?, time: String?) {
self.date = date
self.time = time
}
}
let hoursData = [
Hour(date: "Nov 29, 2015", time: "7"),
Hour(date: "Dec 12, 2015", time: "7"),
Hour(date: "Dec 14, 2015", time: "7"),
Hour(date: "Dec 25, 2015", time: "7") ]
我想知道我该如何创建一个包含当前月份
time
数据之和的变量?或者有几个月的时间?你们能提供的任何帮助都会非常感谢。 最佳答案
我可能会这样做:
// get prefix for current month
let formatter = NSDateFormatter()
formatter.dateFormat = "MMM"
let monthString = formatter.stringFromDate(NSDate())
// now add up the time values for that month
let results = hoursData.filter { $0.date?.hasPrefix(monthString) ?? false }
.reduce(0) { $0 + (Int($1.time ?? "0") ?? 0) }
或者,如果您还想添加一张年份支票:
let formatter = NSDateFormatter()
formatter.dateFormat = "MMM"
let monthString = formatter.stringFromDate(NSDate())
formatter.dateFormat = "yyyy"
let yearString = formatter.stringFromDate(NSDate())
let results = hoursData.filter { $0.date?.hasPrefix(monthString) ?? false && $0.date?.hasSuffix(yearString) ?? false }
.reduce(0) { $0 + (Int($1.time ?? "0") ?? 0) }
print(results)
注意,在上述两种情况下,由于您使用的是选项,因此当值为
??
时,我使用nil
来处理(以及如果time
中有非数字字符串)。就个人而言,我建议
Hour
使用NSDate
和Float
而不是String
,除非确实需要,否则不要使用选项,并使用let
而不是var
:struct Hour {
let date: NSDate
let time: Float
init(dateString: String, time: Float) {
let formatter = NSDateFormatter()
formatter.dateFormat = "MMM, d, y"
self.date = formatter.dateFromString(dateString)!
self.time = time
}
}
然后代码变成:
let hoursData = [
Hour(dateString: "Nov 29, 2015", time: 7),
Hour(dateString: "Dec 12, 2015", time: 7),
Hour(dateString: "Dec 14, 2015", time: 7),
Hour(dateString: "Dec 25, 2015", time: 7),
Hour(dateString: "Dec 25, 2017", time: 7)
]
let calendar = NSCalendar.currentCalendar()
let currentComponents = calendar.components([.Month, .Year], fromDate: NSDate())
let results = hoursData.filter {
let components = calendar.components([.Month, .Year], fromDate: $0.date)
return components.month == currentComponents.month && components.year == currentComponents.year
}.reduce(0) { return $0 + $1.time }
print(results)
可能还有进一步的优化(例如,不重复实例化
NSDateFormatter
),但它说明了使用NSDate
对象可以使用日历计算,而不是查找子字符串的想法。关于swift - 如何在Swift中只得到数组的一部分?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34425881/