Swift documentation states that compactMap() method for sequenced has a time complexity of O(n + m) where n is the length of the sequence and m is the length of the result.
However, when looking at the implementation in the standard library I cannot understand why:
public func _compactMap<ElementOfResult>(
_ transform: (Element) throws -> ElementOfResult?
) rethrows -> [ElementOfResult] {
var result: [ElementOfResult] = []
for element in self {
if let newElement = try transform(element) {
result.append(newElement)
}
}
return result
}
There is only one loop over the sequence elements, it should be O(n).