我有两个看起来像这样的对象数组:
MeetingRoomSuggestions
:
init(suggestionReason: String, organizerAvailability: String,
startTime: String, endTime: String, dStart: Date, availability: String,
emailAddress: String, displayName: String, roomEmail: String,
occupancy: Int, building: String)
和Bookings
:
init(startTime: String, endTime: String, dStart: Date, organizer :
String, location : String, subject : String)
如果MeetingRoomSuggestion
数组中存在dStart
属性,我希望能够从我的数组中过滤/排除Bookings
个对象。
我的代码:
let filteredArr = meetingRoomSuggestions.filter { meeting in
return bookingArray!.contains(where: { booking in
return booking.dStart == meeting.dStart
})
}
我也尝试过滤起始字符串-两者相同。
当我在过滤之前打印出两个数组时,您可以清楚地看到存在与同一dStart
相同的预订。如何排除这个?
使用代码过滤并打印出来后:
print("meetings:")
for meeting in self.meetingRoomSuggestions {
print(meeting.roomEmail)
print(meeting.dStart)
print(meeting.startTime)
}
print()
print("bookings:")
for booking in self.bookingArray! {
print(booking.location)
print(booking.dStart!)
print(booking.start)
}
print("filtered array: ", filteredArr)
for items in filteredArr {
print("email: ", items.roomEmail)
print("dstart: ", items.dStart)
}
返回:
meetings:
FirstFloorTestMeetingRoom1@qubbook.onmicrosoft.com
2019-02-20 15:00:00 +0000
2019-02-20T15:00:00.0000000
GroundFloorTestMeetingRoom1@qubbook.onmicrosoft.com
2019-02-20 15:00:00 +0000
2019-02-20T15:00:00.0000000
bookings:
FirstFloorTestMeetingRoom1@qubbook.onmicrosoft.com
2019-02-20 15:00:00 +0000
2019-02-20T15:00:00.0000000
gfprojectroom1@qubbook.onmicrosoft.com
2019-02-21 10:00:00 +0000
2019-02-21T10:00:00.0000000
gfprojectroom1@qubbook.onmicrosoft.com
2019-02-21 16:00:00 +0000
2019-02-21T16:00:00.0000000
filtered array: [QUBook.MeetingSuggestion, QUBook.MeetingSuggestion]
email: FirstFloorTestMeetingRoom1@qubbook.onmicrosoft.com
dstart: 2019-02-20 15:00:00 +0000
email: GroundFloorTestMeetingRoom1@qubbook.onmicrosoft.com
dstart: 2019-02-20 15:00:00 +0000
由于某种原因,过滤后的数组与原始meetingRoomSuggestions
数组相同-它不会过滤出具有相同dStart
的对象。我怀疑过滤器有问题吗?我以前能够通过将对象与字符串数组等进行比较来过滤对象数组,但不是这样。
答案 0 :(得分:3)
您在这里使用某种反向逻辑。您应该做的是这样:
let filteredArr = meetingRoomSuggestions.filter { meeting in
return !bookingArray.contains(where: { booking in
return booking.dStart == meeting.dStart
})
}
简而言之:filter
个会议,使do not
的{{1}}值等于dStart
中任何对象的dStart
值的会议。