Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create an extension on Swift Array to replace nil with a value?

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))

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 nils 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 }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading