user1898829
user1898829

Reputation: 3527

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

Upvotes: 4

Views: 2949

Answers (2)

AamirR
AamirR

Reputation: 12208

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

Upvotes: 4

ielyamani
ielyamani

Reputation: 18591

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 }

Upvotes: 4

Related Questions