I have one function which is having some logic which have 2 foreach loop but i want to make code compact so I am trying to use compactmap
func getData() -> [String] {
var ids = [String]()
self.item?.connections?.forEach { connection in
connection.validLine?.forEach { line in
if let _ = line.connection?.links[LinkKey.dataGroups],
let dataGroups = line.dataGroupsCache, dataGroups.isContinue {
ids += checkinGroups.connections?.compactMap { $0.id } ?? []
}
}
}
return ids
}
so instead of 2 foreach i am trying to make in one by using self.item?.connections?.compactMap({ $0.validline })
but I am getting error saying "Type of expression is ambiguous without more context"
2
Answers
I don’t see how you can do it without to
forEach
orcompactMap
. Here is a possible solution:Here’s a translation of your post into something that is compilable and a direct translation into a version that doesn’t use forEach.
I changed
connectionIds
toids
in your example because otherwise, you might as well just return[]
.