I tried the following but I continued to get an array of optionals even though I am using compactMap.
let numbers: [Int?] = [2, 4, 5, nil, 8]
extension Array where Element: Equatable {
func replaceNil(with element: Element) -> [Element] {
self.compactMap { $0 == nil ? element : $0 }
}
}
print(numbers.replaceNil(with: 0))
CodePudding user response:
The use of compactMap
is incorrect here. compactMap
turns a [T]
to another [U]
- it is the mapping function that is allowed to return an optional ((T) -> U?
), and it removes any element for which this function returns nil. This property can be used to remove nil
s from a [T?]
and get a [T]
by passing it { $0 }
, but that's not what you are trying to do with the [T?]
in this case.
What you want here is to turn a [T?]
to [T]
, and you have a one-to-one mapping, which can be done with a map
like this:
extension Sequence {
func replacingNil<T>(with element: T) -> [T] where Element == T? {
self.map { $0 ?? element }
}
}