Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CompactMap to filter objects that have nil properties

How do I filter out possible nil values in properties with a compactMap so I don't have to forecast a nil property to return the object.

Currently I have

let objects: [Object] = anotherObject.array.compactMap ({
                        return Object(property: $0.property!)
 })

What I would like is some guard staetment or option to filter out these objects that may have a property that could be nil. For example if $0.property is nil

like image 926
user1898829 Avatar asked Sep 20 '25 10:09

user1898829


2 Answers

You can still use Array.compactMap

With if-statement

anotherObject.array.compactMap { object in
    if let property = object.property {
        return Object(property: property)
    }
    return nil
}

With guard statement

anotherObject.array.compactMap {
    guard let property = $0.property else { return nil }

    return Object(property: property)
}

ternary operator example

anotherObject.array.compactMap { object in
    object.property == nil ? nil : Object(property: object.property!)
}
like image 85
AamirR Avatar answered Sep 23 '25 01:09

AamirR


You could do this :

let objects: [Object] = anotherObject.array.compactMap {
    return $0.property == nil ? nil : $0
}

Or use filter:

let objects: [Object] = anotherObject.array.filter { $0.property != nil }
like image 21
ielyamani Avatar answered Sep 22 '25 23:09

ielyamani