作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在我的应用程序中,我想在应用程序启动时显示通知,说明当天的事件数。到目前为止,我的代码如下所示:
//after appending the arrays with data from api
DispatchQueue.main.async {
print("Dates in array: \(self.datesArray)")
if self.datesArray.contains(dateString){
//check how many events on that day
let newIndex = self.datesArray.index(of: dateString)
print("newIndex: ", newIndex!)// position of current date
print("Events today: ", self.datesArray)
self.notificationPublisher.sendNotification(title: "Events", subtitle: "", body: "\(self.datesArray.count) today", delayInterval: nil )
} else {
self.notificationPublisher.sendNotification(title: "Events", subtitle: "", body: "No events today", delayInterval: nil)
}
}
我想过以某种方式找到一种方法来填充 datesArray
数组,这样我就可以显示当天的事件数,但我不确定该怎么做。我的处理方式是否正确?
编辑:我从这里使用了一种检查数组中重复元素的方法:How to count occurrences of an element in a Swift array?
所以现在我的代码看起来像这样:`DispatchQueue.main.async { print("数组中的日期:(self.datesArray)")
if self.datesArray.contains(dateString){
self.datesArray.forEach{self.counts[$0, default: 0] += 1}
print("Counts: ", self.counts)
self.notificationPublisher.sendNotification(title: "Events", subtitle: "", body: "No events today", delayInterval: nil)
}
}`
Count 输出所有数组元素以及它们出现的次数。我如何使用该数据来显示特定日期有多少事件?
最佳答案
检查你的 self.datesArray
是否有一些值,
print(self.datesArray)
并计算今天的事件数为:
let todayEvent = self.datesArray.filter({ $0 == dateString })
总计:
let datesArray = ["2018-08-21", "2018-08-10", "2018-08-30", "2018-09-17", "2018-08-21", "2018-09-17"]
fileprivate lazy var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}()
func postNotificationForTodaysEvent() {
print("Dates in array: \(self.datesArray)")
DispatchQueue.main.async {
let dateString = self.dateFormatter.string(from: Date())
let todayEvent = self.datesArray.filter({ $0 == dateString }) // It will fetched the event from same date
print(todayEvent)
if todayEvent.isEmpty {
self.notificationPublisher.sendNotification(title: "Events", subtitle: "WeAsean", body: "No events today", delayInterval: nil)
} else {
self.notificationPublisher.sendNotification(title: "Events", subtitle: "WeAsean", body: "\(todayEvent.count) today", delayInterval: nil )
}
}
}
结果将是:
Dates in array: ["2018-08-21", "2018-08-10", "2018-08-30", "2018-09-17", "2018-08-21", "2018-09-17"]
today's events are:["2018-09-17", "2018-09-17"]
关于ios - 在 Swift 中获取某一天的事件数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52362380/
我是一名优秀的程序员,十分优秀!