swift - 如何避免提醒应用程序中的重复条目?
问题描述
我目前正在为学校开发一个提醒类型的应用程序。您插入年、月、日、小时和分钟,然后将这些值添加到数组中。我想这样做,如果要再次输入那些完全相同的值,它就不会被添加到数组中。例如:我在 6:30 输入 25/12/2019。如果我再次输入完全相同的时间,它不会将所有值添加到数组中,但如果我在 6:31 输入 25/12/2019,它会将所有值添加到数组中。
monthDuplicate
是 的重复数组remindMonth
,其中包含月份的所有值。前面带有“提醒”的任何内容都是它们各自值的数组。任何带有“设置!”的东西 在它的末尾是其各自值的文本字段。isProperTime()
只是一个运行其余代码的函数(向数组添加内容的代码)
我很不擅长解释这一点,而且对编程也很陌生,所以如果有人需要对我的漫无边际的解释进行任何澄清,我会很高兴地答应。任何帮助将不胜感激。
while monthDuplicate.contains(monthSet!) {
if let index = remindMonth.firstIndex(of:monthSet!) {
print(remindMonth)
if remindYear[index] == yearSet! && remindDay[index] == daySet! && remindHour[index] == hourSet! && remindMinute[index] == minuteSet! {
reminderError.text = "Reminder already exists"
monthDuplicate.remove(at: index)
} else {
isProperTime()
}
}
}
isProperTime()
解决方案
为几天、几个月和几年创建单独的数组是过度和浪费的。为什么不将输入日期存储为Dates()
类型,并将它们存储在数组中,然后将数组转换为排序Set
日期但删除重复并保留Date()
类型的排序。
let datesArray = ["Wed, 25 Dec 2019 06:30", "Wed, 25 Dec 2019 06:31", "Wed, 25 Dec 2019 06:31", "Wed, 25 Dec 2019 06:32"]
var noDuplicates = [Date]()
for dates in datesArray{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "E, d MMM yyyy HH:mm"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
if let date = dateFormatter.date(from: dates){
noDuplicates.append(date)
}
}
let orderedDates = Array(Set(noDuplicates).sorted())
output: [2019-12-25 06:30:00 +0000, 2019-12-25 06:31:00 +0000, 2019-12-25 06:32:00 +0000]
或将它们放入一个 NSOrderedSet 中,该集合还保留顺序并删除重复项,但会将数组类型从类型更改Dates()
为Any()
类型。
let orderedDates = NSOrderedSet(array: noDuplicates).array
output: [2019-12-25 06:30:00 +0000, 2019-12-25 06:31:00 +0000, 2019-12-25 06:32:00 +0000]
推荐阅读
- android - 如果在前台应用程序时点击消息,nativescript-plugin-firebase 云消息传递应用程序崩溃
- python - 串行端口 - 无法读取数据,我只是写了
- python - 我可以从 Python 中的 html 文件中抓取表格吗?
- javascript - 有人可以帮助解决以下 GAS 代码的问题吗
- typescript - 如何在 Array.find 方法中保持类型缩小?
- linux - Docker Container:Cronjobs 未启动(确定我的错误)
- quantum-computing - 如何在 Cirq/Tensorflow Quantum 中实现受控 Rx?
- python - Python 加速请求
- javascript - 使用键迭代数组时是否保证顺序?
- java - 从Java中的字符串中提取正确的类型