I have a simple function to find a specific element by index in an array using firstIndex
like this, where Entry.id
is a String
:
private func findUserEntry(inEntries entries: [Entry],
currentUserID: String?) -> Entry? {
guard let currentUserID = currentUserID else { return nil }
guard let index = entries.firstIndex(where: { $0.id == currentUserID }) else { return nil }
return entries[index]
}
I was refactoring my code to try to accomplish the same thing in different ways, as a way to learn and practice. I thought this function would effectively do the same thing:
private func findUserEntry(inEntries entries: [Entry],
currentUserID: String?) -> Entry? {
guard let currentUserID = currentUserID else { return nil }
return entries
.firstIndex { $0.id == currentUserID }
.map { possibleIndex -> Entry? in
guard let index = possibleIndex else { return nil }
return entries[index]
}
}
However, I'm running into an error: Initializer for conditional binding must have Optional type, not 'Array<Entry>.Index' (aka 'Int')
. So, somehow, the value of possibleIndex
coming out of .firstIndex
into .map
is an Int
instead of the Int?
I expected, like it is in the original version above. Why is there a difference here?