I have 7 arrays of Strings
.
var redArray : [String] = ["2022-07-13", "2022-07-14","2022-07-15"]
var blueArray : [String] = ["2022-07-13", "2022-07-14","2022-07-16"]
...
And five more of the same format
I’m trying to create a method that will go through seven arrays and work like the following one (example below works for two arrays):
if redArray.contains(someDate) && blueArray.contains(someDate)
{
return [UIColor.red, UIColor.blue]
}
else
if redArray.contains(someDate)
{
return [UIColor.red]
}
else if blueArray.contains(someDate)
{
return [UIColor.blue]
}
return [UIColor.clear]
So it should find matches of dates in arrays and return an UIColor
of arrays with this matches. In case there is no match – a single colour should be returned. It’s easy to do it for two arrays. But I don’t understand how can I loop through 7 of them 🙁
Of course, it can be done manually. But I guess there must be a smart way to implement the loop
– though I’m not smart enough to figure it out how.
P.S. I don’t know, if it is important, but the function
where this method will be used is the following:
func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance,eventDefaultColorsFor date: Date) -> [UIColor]?
{
...
}
2
Answers
Try this:
Usage:
loop(someDate: "some Date", arrays: [(["Test1"], .red), (["Test2"], .blue)])
You could simply do that:
If you really want loops, starting with:
Basic for loop:
Basic for loop with
where
:With a
forEach
:If you prefer
reduced(into:_:)
:And still
return colors.isEmpty ? [.clear] : colors
at the end.Edit: As suggested in comments, there is also the
compactMap()
solution. It can be seen as amap()
+filter()
in one loop.