我想得到这个结果:
var eventDate: [DateComponents: EventType] = [
DateComponents(calendar: Calendar(identifier: .gregorian), year: 2024, month: 7, day: 04): .busy,
DateComponents(calendar: Calendar(identifier: .gregorian), year: 2024, month: 8, day: 07): .busy,
DateComponents(calendar: Calendar(identifier: .gregorian), year: 2024, month: 10, day: 16): .busy,
DateComponents(calendar: Calendar(identifier: .gregorian), year: 2024, month: 12, day: 17): .busy,
DateComponents(calendar: Calendar(identifier: .gregorian), year: 2025, month: 4, day: 18): .busy,
DateComponents(calendar: Calendar(identifier: .gregorian), year: 2026, month: 9, day: 26): .busy
]
我正在尝试这种方式,但我没有得到我想要的。我不明白你一开始看到的列表。
func dateTimestampDividedInt(date: TimeInterval) -> (year: Int, month: Int, day: Int) {
let calendar = Calendar.current
let date = Date(timeIntervalSince1970: date)
let day = calendar.component(.day, from: date)
let month = calendar.component(.month, from: date)
let year = calendar.component(.year, from: date)
return (year, month, day)
}
for employee in eventArrayIcon {
let timeIntervalDateEndDivided = employee.dateEnd?.dateTimestampDividedInt(date: employee.dateEnd ?? 0.0)
let yearInt = timeIntervalDateEndDivided?.year
let monthInt = timeIntervalDateEndDivided?.month
let dayInt = timeIntervalDateEndDivided?.day
eventDate = [
DateComponents(calendar: Calendar(identifier: .gregorian), year: yearInt, month: monthInt, day: dayInt): .busy
]
}
让我们简化并关注
Dictionary
的工作原理,因为所有 DateComponents
都会让事情变得吵闹。
您可以停止正在做的事情,打开 Playground 并进行测试,以确保您对 Dictionary
的理解是最新且正确的。
您当前正在做什么:每次设置
myDic1
的整个值
即:忘记你以前的价值观,现在你只是["Key\(i)": "Value \(i)"]
所以它的输出将是最后一个覆盖,即 myDic1 = ["Key\(4)": "Value \(4)"]
var myDic1: [String: Any] = [:]
for i in 0...4 {
myDic1 = ["Key\(i)": "Value \(i)"]
print("Partial1: \(myDic1)")
}
print("Final1: \(myDic1)")
您想要的是为每个新键设置值:
var myDic2: [String: Any] = [:]
for i in 0...4 {
myDic2["Key\(i)"] = "Value \(i)"
print("Partial1: \(myDic2)")
}
print("Final2: \(myDic2)")
但对于字典来说,键是唯一的。这意味着如果你这样做:
myDict[key] = Value0
myDict[key] = Value1
然后,
myDict[key]
将是 Value1
(即,key
的最后一个设置。
var myDic3: [String: Any] = [:]
for i in 0...4 {
myDic3["Key\(i)"] = "Value \(i)"
print("Partial3: \(myDic3)")
}
for i in 0...4 {
myDic3["Key\(i)"] = "New Value \(i)"
print("Partial3: \(myDic3)")
}
print("Final3: \(myDic3)")
因此,在您的情况下,如果不同员工的键
DateComponents(calendar: Calendar(identifier: .gregorian), year: yearInt, month: monthInt, day: dayInt)
相同,您将仅获得最后设置的值。所以你需要改变你的模型。
我不知道你想用你的模型做什么,但是 var eventDate: [DateComponents: [EventType]]
可能是一个解决方案,这意味着你可以为同一个 DateComponents
拥有多个 EventType,等等。